【发布时间】:2014-03-21 03:21:30
【问题描述】:
假设有一个data.frame,其中一些变量被编码为整数:
a <- c(1,2,3,4,5)
b <- as.integer(c(2,3,4,5,6))
c <- as.integer(c(5,1,0,9,2))
d <- as.integer(c(5,6,7,3,1))
e <- c(2,6,1,2,3)
df <- data.frame(a,b,c,d,e)
str(df)
假设我想将列 b 到 d 转换为数字:
varlist <- names(df)[2:4]
lapply(varlist, function(x) {
df$x <- as.numeric(x, data=x)
})
str(df)
不工作。
我试过了:
df$b <- as.numeric(b, data=df)
df$c <- as.numeric(c, data=df)
df$d <- as.numeric(d, data=df)
str(df)
效果很好。
问题:
我该如何做到这一点(在循环中或使用lapply 更好,[但我是 Stata 人,因此习惯于编写循环])?
更一般地说:如何将任何函数应用于 data.frame 中的变量列表
(例如,将列表中的每个变量与其他变量相乘[始终保持不变,
奖励:或随列表中的每个变量而变化])?
【问题讨论】: