规避 ifelse() 限制以将 156 个唯一值插入大型数据帧
Circumventing the ifelse() limit to insert 156 unique values to a large-scale dataframe
我的数据框包含 784,081 家公司 * 13 年 = 10,193,053 个独特的 firm_year 观察结果(例如 firm1_2007、firm1_2008、firm1_2009、......、. ....., firm784,081 2018, firm784,081 2019 ) 来自12个国家。
现在,我想插入一个列“gdpgrowthpercapita”。我有 13 * 12=156 个唯一值(小数,例如 3.34587),具体取决于要插入的年份和祖国。
首先,我尝试嵌套 ifelse() 语句。这通常有效,但是,有 50 个嵌套语句的 limit; >50 的所有内容均无效(请参阅此处:Is there a limit for the possible number of nested ifelse statements)
接下来,我尝试为每个国家编写 ifelse() 语句的“块”;然而,问题是 ifelse(test, yes, no) 中的 no argument 不能被忽略,或者 - 据我所知 - 以不触及其中的字段的方式设置测试不适用。
如何编写变量代码?
感谢您的帮助!希望我错过了一个明显的方式 - 作为 R 菜鸟。
提前致谢!
最好的,
莫
您不需要嵌套 ifelse
语句 - 只需提前将列定义为 NA,然后重复填写即可。对于 no
参数,您可以提供列本身,它会智能地填充值:
df <- head(data.frame(letters, LETTERS))
df$newcol <- NA
df$newcol <- ifelse(test = is.na(df$newcol) & df$letters=="a",
yes = "this is an a",
no = df$newcol)
df$newcol <- ifelse(test = is.na(df$newcol) & df$letters=="b",
yes = "this is a b",
no = df$newcol)
> df
letters LETTERS newcol
1 a A this is an a
2 b B this is a b
3 c C <NA>
4 d D <NA>
5 e E <NA>
6 f F <NA>
我的数据框包含 784,081 家公司 * 13 年 = 10,193,053 个独特的 firm_year 观察结果(例如 firm1_2007、firm1_2008、firm1_2009、......、. ....., firm784,081 2018, firm784,081 2019 ) 来自12个国家。
现在,我想插入一个列“gdpgrowthpercapita”。我有 13 * 12=156 个唯一值(小数,例如 3.34587),具体取决于要插入的年份和祖国。
首先,我尝试嵌套 ifelse() 语句。这通常有效,但是,有 50 个嵌套语句的 limit; >50 的所有内容均无效(请参阅此处:Is there a limit for the possible number of nested ifelse statements)
接下来,我尝试为每个国家编写 ifelse() 语句的“块”;然而,问题是 ifelse(test, yes, no) 中的 no argument 不能被忽略,或者 - 据我所知 - 以不触及其中的字段的方式设置测试不适用。
如何编写变量代码?
感谢您的帮助!希望我错过了一个明显的方式 - 作为 R 菜鸟。
提前致谢!
最好的, 莫
您不需要嵌套 ifelse
语句 - 只需提前将列定义为 NA,然后重复填写即可。对于 no
参数,您可以提供列本身,它会智能地填充值:
df <- head(data.frame(letters, LETTERS))
df$newcol <- NA
df$newcol <- ifelse(test = is.na(df$newcol) & df$letters=="a",
yes = "this is an a",
no = df$newcol)
df$newcol <- ifelse(test = is.na(df$newcol) & df$letters=="b",
yes = "this is a b",
no = df$newcol)
> df
letters LETTERS newcol
1 a A this is an a
2 b B this is a b
3 c C <NA>
4 d D <NA>
5 e E <NA>
6 f F <NA>