如何根据现有变量创建新的r数据帧变量 [英] How to create a new r dataframe variable contingent on existing variables

查看:461
本文介绍了如何根据现有变量创建新的r数据帧变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关在数据框中创建新变量的最佳逻辑的建议是否取决于数据框中的其他变量?

Any suggestions on the best logic to create a new variable in a r data frame that is contingent on other variables in the dataframe?

基本上,我有一个类型变量在一个数据框中,我想覆盖在第二个数据帧中包含的certian实例中。以下是一些示例数据:

Essentially, I have a type variable in one data frame that I want to overide in certian instances which are contained in a second dataframe. Below is some sample data:

#### original data frame
id=c(1,2,3,4,5,6)
type=c("O", "O", "G", "O", "G", "O")
qty=c(10,20,30,40,50,60)
df1=data.frame(id, type, qty)

#### new dataframe with type override
id=c(2,4)
type_override=c("G", "G")
df2=data.frame(id,type_override)

#### dataframe with both origional and override type
df3=merge(df1, df2, by=c("id"), all.x=TRUE)

#### create new type variable that uses "type" for all variables
#### unless "type_override" calls for a override
df3$type_new= ???????

我想在第二个数据帧中使用类型分类(即type_override)来覆盖类型分类(即第一个数据框中的类型。

I would like to use the type classification (i.e. "type_override") in the second dataframe to override the type classification (i.e. "type" in the first dataframe.

我是一个试图转换到R的Excel用户,在Exel中,我只会做一些事情喜欢:

I am an Excel user that is trying to make the transition to R, in Exel, I would just do something like:

type_newC1 = if(isna(type_overrideB1),typeA1,type_overrideB1)

非常感谢任何帮助。

推荐答案

如果你的df2只与一种类型一起使用,你可以一步到位:

If your df2 will be used with only a single type, you can get away with a single step:

df1$type_override <- ifelse(df1$id %in% df2$id, df2$type_override, df1$type)

这篇关于如何根据现有变量创建新的r数据帧变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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