您可能还需要考虑使用transform()
处理重新编码此类问题。 transform()
将执行比逻辑索引方法慢的速度,但更容易消化代码的意图。关于不同方法的优缺点可以参考here。试想一下:
set.seed(42)
df <- data.frame("first" = sample(1:5, 10e5, TRUE), "second" = sample(4:8, 10e5, TRUE))
df <- transform(df
, test = ifelse(first %in% 1:3 & second == 4, 1
, ifelse(first %in% 1:3 & second == 5, 2
, ifelse(first %in% 1:3 & second == 6, 3, NA)))
)
其次,列名1st
和2nd
不是语法有效的列名。查看make.names()
了解有效列名称的更多详细信息。使用data.frame
时,可以使用/滥用check.names
参数。例如:
> df <- data.frame("1st" = sample(1:5, 10e5, TRUE), "2nd" = sample(4:8, 10e5, TRUE), check.names = FALSE)
> colnames(df)
[1] "1st" "2nd"
> df <- data.frame("1st" = sample(1:5, 10e5, TRUE), "2nd" = sample(4:8, 10e5, TRUE), check.names = TRUE)
> colnames(df)
[1] "X1st" "X2nd"
非常感谢aix!问题确实是1:3;拼写出来工作。 – dw006 2010-12-13 11:58:35
+1供参考。 – Marek 2010-12-13 14:05:30