【问题标题】:How to modify some but not all variables of a data frame?如何修改数据框的部分但不是全部变量?
【发布时间】: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 中的变量列表
(例如,将列表中的每个变量与其他变量相乘[始终保持不变,
奖励:或随列表中的每个变量而变化])?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    第一个问题可以使用sapply:

    df[2:4] <- sapply(df[2:4],as.numeric)
    

    第二个你应该使用mapply。例如,将 3 个变量(2 到 4)乘以 3 个不同的随机标量:

    df[2:4] <-  mapply(function(x,y)df[[x]]*y,2:4,rnorm(3))
    

    【讨论】:

      【解决方案2】:
      df[,2:4] <- sapply(df[,2:4], as.numeric)
      

      至于你的第二个问题,如果你想说将 c 列乘以 5

      df$c <- df$c * 5
      

      或任何与 c 长度相同的向量,可能是一个将 c 乘以 d 的新列

      df$cd <- df$c * df$d
      

      【讨论】:

      • 也谢谢。但是 agstudy 也以apply 格式给出了第二个答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 1970-01-01
      • 2023-02-04
      • 2017-03-08
      相关资源
      最近更新 更多