使用R根据其他列创建新变量 [英] Create new variable based on other columns using R

查看:143
本文介绍了使用R根据其他列创建新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a huge file where I want to create a column based on other columns. My file look like this:

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函数来解决这个问题。谢谢。

And I want to create a column indicating if the person is a father or mother (gender column). I got it using a for loop in a small example, but when I apply in the whole file it takes hours to finish. How can I create an apply function to solve that, please. Thanks.

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


推荐答案

尝试一下:

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

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

Instead of looping over the individual values across the rows, this uses vectorization.

这篇关于使用R根据其他列创建新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆