通常,当以编程方式使用 dplyr 时,我希望通过名称选择列,其中列名称作为字符串存储在某个变量中。
我注意到尝试使用 dplyr 执行此操作通常会导致意外结果。这似乎是由于 tbl_df 的处理方式造成的。
以下是一些示例:
## regular data frame:
df = data.frame(subject = 1:3, resp = c(2,3,3)) # example dataframe
response_column = "resp" # I want to select the contents of a column with a string
# for loop over unique values:
unique_responses = unique(df[,response_column])
for (resp in unique_responses) {
cat("\nA response:", resp)
}
# convert column type:
df[,response_column] = as.character(df[,response_column])
str(df) # modified the column
这些是我习惯做的事情。访问列的内容、转换它们并重新分配它们、获取它们的唯一值等。
但是当 data.frame 具有类 tbl_df 和 tbl 时,事情就不起作用了。
## with tbl_df and tbl
require(dplyr)
df = data.frame(subject = 1:3, resp = c(2,3,3))
class(df) = c("tbl_df","tbl", class(df))
class(df)
df[,response_column]
# for loop doesn't seem to know what to do with this:
unique_responses = unique(df[,response_column])
for (resp in unique_responses) {
cat("\nA response:", resp)
}
# as.character seems to concatenate the entire column into one string!
df[,response_column] = as.character(df[,response_column])
df
我不确定如何看待这种行为(即故意与错误),或者一般来说,最佳实践是什么是能够在正常数据帧以及 dplyr 的数据帧中使用相同的(编程)代码。