规避 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),具体取决于要插入的年份和祖国。

如何编写变量代码?

感谢您的帮助!希望我错过了一个明显的方式 - 作为 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>