質問

変数で何をすべきかを暗示する変数名を組み込みたい。データフレームの「調査」を想像します。

library(Rlab) # Needed for rbern() function.
survey <- data.frame(cbind(  
id = seq(1:10),  
likert_this = sample(seq(1:7),10, replace=T),  
likert_that = sample(seq(1:7), 10, replace=T),  
dim_bern_varx = rbern(10, 0.6),  
disc_1 = sample(letters[1:5],10,replace=T)))

今、 likert を含むすべての変数で特定のことを行い、 bern を含む変数で他のことを行います。

これをRで実行するにはどうすればよいですか

役に立ちましたか?

解決

colnames() grep()を使用できます:

survey[,grep("bern", colnames(survey))]

他のヒント

取得したい一連の名前がある場合は、matchも使用できます。おそらく、変数「パルス」、「運動」、「高さ」、「重量」が必要になることがよくあります。と「年齢」がありますが、異なる場所や他の変数が追加されている場合があります。共通名のベクトルを保存してからデータフレームと照合し、標準列のみの新しいdfを希望する順序で保持できます。

basenames <- c("pulse", "exercise", "height", "weight", "age")
get.columns <- match(basenames, names(dataframe))
new.df <- dataframe[,get.columns]

「演算子」パッケージはPerlのような構文を許可します:

library(operators)

survey[, colnames(survey) %~% "bern"]

または

subset(survey, select = colnames(survey) %~% "bern")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top