r - 结合 ifelse 两个条件并循环
问题描述
我有一个数据框列表(file1、file2、...、file 72)。对于每个数据框,我想根据两个条件创建一个包含来自另一个数据框的信息的变量。
这个想法很简单:
- 条件 1:如果 file*$countryid 等于 source$country,并且
- 条件 2:如果 file*$year 高于 source$starting 但低于 source$ending,那么如果为真,我想创建一个列 file*$rank,其值为 source$rank
我一直在尝试这样的代码行,但这段代码并没有遍历源代码中的所有行:
file1$rank<-ifelse(file1$countryid=source$countryid & file1$year>source$starting & file1$year<source$ending,source$rank,NA)
此外,我想在循环中实现这一点,以避免手动迭代所有这些数据帧:
dflist<-Filter(is.data.frame, mget(ls()))
dflist<-function(df,x){df$rank<-ifelse(df$countryid=source$countryid & df$year>source$starting & df$year<source$ending,source$rank,NA))
这是我拥有的数据的示例。谢谢!
> dput(file1)
structure(list(id = c(1, 2, 3), countryid = c(10, 10, 13), year = c(1948,
1954, 1908)), row.names = c(NA, -3L), class = c("tbl_df", "tbl",
"data.frame"))
dput(file2)
structure(list(id = c(1, 2, 3), countryid = c(13, 10, 13), year = c(1907,
1908, 1907)), row.names = c(NA, -3L), class = c("tbl_df", "tbl",
"data.frame"))
> dput(source)
structure(list(country = c(13, 13, 13, 10, 10, 10), rank = c(1,
2, 3, 1, 2, 3), starting = c(1885, 1909, 1940, 1902, 1907, 1931
), ending = c(1908, 1939, 1960, 1906, 1930, 1960)), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
解决方案
在将所有file\\d+
数据集放入一个list
library(data.table)
out <- lapply(mget(ls(pattern = '^file\\d+$')), function(dat)
setDT(dat)[, year := as.integer(year)][as.data.table(source), rank := i.rank,
on = .(countryid = country, year > starting, year < ending)])
-输出
out
#$file1
# id countryid year rank
#1: 1 10 1948 3
#2: 2 10 1954 3
#3: 3 13 1908 NA
#$file2
# id countryid year rank
#1: 1 13 1907 1
#2: 2 10 1908 2
#3: 3 13 1907 1
如果需要更新原始对象,请使用list2env
list2env(out, .GlobalEnv)
推荐阅读
- python - 无法在 Django 中获取登录用户的数据
- jquery - 使用 jQuery 设置图标字体(在 Divi WP 主题的自定义切换中)
- javascript - 从 React 组件调用功能组件中的函数
- oracle - Oracle 更改子分区 lob 索引的默认属性
- android - Cordova 无法在 Android Studio 或您的系统上找到已安装的 Gradle 版本以安装 gradle 包装器
- python - ImportError:无法从“gensim.utils”导入名称“has_pattern”
- python - LSTM 模型最后一个线性层
- php - Docker mysql 找不到驱动程序
- tensorflow - 如何为 TF hub TFv2 模型执行修剪(子图提取),TF hub v1 模型的 tf.saved_model.load() 支持类似的功能
- python - HTCondor:根据 SysExitCode 重新提交作业或终止作业