【问题标题】:Create new variable based on other columns using R使用 R 基于其他列创建新变量
【发布时间】:2015-08-01 02:46:49
【问题描述】:

我有一个巨大的文件,我想在其中创建一个基于其他列的列。 我的文件如下所示:

person = c(1,2,3,4,5,6,7,8)
father = c(0,0,1,1,4,5,5,7)
mother = c(0,0,2,3,2,2,6,6)
ped = data.frame(person,father,mother)

我想创建一个列来指示此人是父亲还是母亲(性别列)。我在一个小例子中使用 for 循环得到它,但是当我在整个文件中应用时,需要几个小时才能完成。请问如何创建一个应用函数来解决这个问题。谢谢。

for(i in 1:nrow(ped)){
  ped$test[i] = ifelse(ped[i,1] %in% ped[,2], "M", ifelse(ped[i,1] %in% ped[,3], "F", NA)) 
}

【问题讨论】:

    标签: r for-loop dataframe


    【解决方案1】:

    试试这个:

    ped <- transform(ped, gender = ifelse(person %in% father,
                                          'M',
                                          ifelse(person %in% mother, 'F', NA)
                                         ))
    

    这不是在行间循环单个值,而是使用矢量化。

    【讨论】:

    • 非常感谢@B.Shankar。
    【解决方案2】:

    你可以试试

    ped$gender <- c(NA, 'M', 'F')[as.numeric(factor(with(ped, 
                      1+2*person %in% father + 4*person %in% mother)))]
    

    或者更快的选择是将:= 分配给data.table

    library(data.table)
    setDT(ped)[person %in% father, gender:='M'][person %in% mother, gender:='F']
    

    【讨论】:

      【解决方案3】:

      无需在代码中指定每个“父亲”/“母亲”/等选项,您可以这样做:

      vars <- c("father","mother")
      factor(
        do.call(pmax, Map(function(x,y) (ped$person %in% x) * y, ped[vars], seq_along(vars) )),
        labels=c(NA,"M","F")
      )
      #[1] M    F    F    M    M    F    M    <NA>
      #Levels: <NA> M F
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-29
        相关资源
        最近更新 更多