使用R基于其他列创建新变量

时间:2015-05-20 03:26:35

标签: r for-loop dataframe

我有一个巨大的文件,我想根据其他列创建一个列。 我的文件看起来像这样:

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)) 
}

3 个答案:

答案 0 :(得分:3)

试试这个:

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

不是循环遍历各行的各个值,而是使用矢量化。

答案 1 :(得分:3)

你可以尝试

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']

答案 2 :(得分:2)

无需在代码中指定每个“father”/“mother”/ etc选项,您可以执行以下操作:

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
相关问题