[英]Replacing values using a list in R
I have a large dataframe, and am trying to count up the scores of many questions.我有一个大的 dataframe,并且正在尝试计算许多问题的分数。 Here is some sample data.这是一些示例数据。
Q1 = c("apple", "banana", "cider", "muffin", "chocolate")
Q2 = c("orange", "kiwi", "calzone", "cupcake", "cake")
ID = c("P1", "P2", "P3", "P4", "P5")
mydf = data.frame(Q1,Q2,ID)
answer_key = c("apple", "kiwi", "pizza", "dessert", "cake")
I've been trying to use ifelse and %in% for the whole dataframe我一直在尝试对整个 dataframe 使用 ifelse 和 %in%
mydf = ifelse(mydf %in% answer_key, 1,0)
but it doesn't work, and it returns a vector when I need a dataframe.但它不起作用,当我需要 dataframe 时它会返回一个向量。 I just want to replace my values without having to do this for each question because there are many:我只想替换我的价值观,而不必为每个问题都这样做,因为有很多:
mydf$Q1 <-ifelse(mydf$Q1 == "apple", 1, 0)
mydf$Q2 <-ifelse(mydf$Q2 == "kiwi", 1, 0)
Perhaps this is what you're looking for?也许这就是你要找的?
library(dplry)
mydf %>%
mutate(across(Q1:Q2,~ +(. %in% answer_key)))
Q1 Q2 ID
1 1 0 P1
2 0 1 P2
3 0 0 P3
4 0 0 P4
5 0 1 P5
Or a bit messy with base R:或者对基础 R 有点混乱:
mydf[,c("Q1","Q2")] <- sapply(mydf[,c("Q1","Q2")],function(x) +(x%in%answer_key))
mydf
Q1 Q2 ID
1 1 0 P1
2 0 1 P2
3 0 0 P3
4 0 0 P4
5 0 1 P5
I hope this is what you are looking for:我希望这是您正在寻找的:
library(dplyr)
mydf %>%
mutate(across(Q1:Q2, ~ ifelse(.x %in% answer_key, 1, 0)))
Q1 Q2 ID
1 1 0 P1
2 0 1 P2
3 0 0 P3
4 0 0 P4
5 0 1 P5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.