【发布时间】:2019-11-14 03:54:27
【问题描述】:
我正在尝试使用列中的值来提取数据框中的列号。我的问题类似于r-bloggers 中的这个主题。在此处复制脚本:
df <- data.frame(x = c(1, 2, 3, 4),
y = c(5, 6, 7, 8),
choice = c("x", "y", "x", "z"),
stringsAsFactors = FALSE)
但是,我在choice 中没有列名,而是列索引号,这样我的数据框看起来像这样:
df <- data.frame(x = c(1, 2, 3, 4),
y = c(5, 6, 7, 8),
choice = c(1, 2, 1, 3),
stringsAsFactors = FALSE)
我尝试使用此解决方案:
df$newValue <-
df[cbind(
seq_len(nrow(df)),
match(df$choice, colnames(df))
)]
而不是给我一个看起来像这样的输出:
# x y choice newValue
# 1 1 4 1 1
# 2 2 5 2 2
# 3 3 6 1 6
# 4 8 9 3 NA
我的 newValue 列返回所有 NA。
# x y choice newValue
# 1 1 4 1 NA
# 2 2 5 2 NA
# 3 3 6 1 NA
# 4 8 9 3 NA
我应该在代码中修改什么,以便它将我的choice 列读取为列索引?
【问题讨论】:
-
查看
match(df$choice, colnames(df))- 你的列没有命名为"1""2"等等,所以match不起作用。 -
@thelatemail 你有建议的解决方法吗?
-
Ronak 已经把它盖住了。
标签: r indexing extraction