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

3

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

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循环获得了它,但当我在整个文件中应用时,它需要数小时才能完成。请问如何创建一个apply函数来解决这个问题。谢谢。

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个回答

3

试试这个:

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

这里使用向量化方法,而不是遍历行中的各个值。


非常感谢@B.Shankar。 - PaulaF

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接