r - R data.table 如何根据另一列的值从许多列中的一个(按列名称)获取值
问题描述
我正在尝试通过引用列名从 R 中的 data.table 中提取特定值
require(data.table)
# Create data.frame
cohort = c("cohort1", "cohort2", "cohort3")
year = c(2019, 2018, 2020)
item_2018 = c("alpha", "beta", "gamma")
item_2019 = c("banana", "apples", "oranges")
item_2020 = c("Tim", "Daniel","Simon")
desired_result = c("banana", "beta", "Simon") # the values in this column I want to programatically grab from the relevant column before
cohorts <- data.frame(cohort,year, item_2018, item_2019, item_2020, desired_result)
setDT(cohorts) # turn the data.frame into a data.table
setkey(cohorts, year) # setting the key for the data.table (not sure if this is necessary)
# CALCULATE NEW FIELD (attempts - not working)
# trying to populate new column "result_attempt_1" with : c("banana", "beta", "Simon")
cohorts[, result_attempt_1 := get(paste0("item_", year)), by = year] # this returns c("Simon", "Simon", "Simon") rather than c("banana", "beta", "Simon")
cohorts[, result_attempt_2 := .SD[, get(paste0("item_", year)), by = year]] # very wrong
cohorts[, result_attempt_3 := .SD[, get(paste0("item_", year)), by = get(paste0("item_", year))]] # very wrong
我希望“desired_results”列中的值最终出现在“result_attempt”列中。我得到的最接近的是为每条记录/行重复的最后一个正确结果。
任何想法如何实现这一目标?非常感谢。
解决方案
使用的另一个选项data.table::melt
,匹配 item_year 然后通过引用查找和更新:
cohorts[
melt(cohorts, measure.vars=patterns("^item"), variable.factor=FALSE)[,
value[variable==paste0("item_", year)], by=.(cohort)],
on=.(cohort), desired_result := V1]
推荐阅读
- javascript - 如何在jquery中自动打印时删除不需要的内容,如url
- java - 无法解析根:缺少要求 [root] osgi.identity
- sql - 如何在 JSON_EXISTS Oracle SQL Developer 中使用双引号传递参数
- python - 使用 I/O 运行 Dockerized Python 应用程序
- c++ - 通过可变参数模板函数的参数包以相反的顺序迭代
- python - 使用请求进行身份验证后的 Web 抓取
- mysql - 提取由相似分隔符分隔的子字符串 MYSQL
- python - 在python中求解非线性方程
- android - 购买场景中的应用内购买问题 - Kotlin
- laravel - 使用 Fortify Laravel 进行电子邮件确认