我有DF1
:
DF1 <- data.frame(Before = factor(c("Bad", "Bad", "Good", "Good", "Bad", "Bad")),
Now = factor(c("Good", "Good", "Good", "Bad", "Bad", "Good")))
我想基于因子Change
和Before
的值创建一个新因子Now
,以便从Bad
中的Before
变为{ Good
中的{1}}是新因子中的Now
,依此类推:
Better
如何实现?
答案 0 :(得分:1)
在基本R中尝试以下操作:
this.getters.reservationsCurrentWeek
或使用mutations: {
YOUR_MUTATION(state, {data, getters}) {
console.log(getters);
}
}
:
DF1$Change <- unlist(Map(function(x,y){
if (x==y){
return("No change")
} else if (x=="Bad"){
return("Better")
} else {
return("Worse")
}
}, DF1$Before, DF1$Now))
输出:
purrr
答案 1 :(得分:1)
以下函数根据值"Good"
和"Bad"
创建一个新列。
change <- function(x, y){
n <- length(x)
x <- as.character(x)
y <- as.character(y)
out <- rep("Better", n)
out[x == y] <- "No change"
out[x > y] <- "Worse"
out
}
DF2 <- DF1
DF2$Change <- change(DF2$Before, DF2$Now)
DF2
# Before Now Change
#1 Bad Good Better
#2 Bad Good Better
#3 Good Good No change
#4 Good Bad Worse
#5 Bad Bad No change
#6 Bad Good Better
此功能也可以在magrittr
管道中,输出到DF2
。
library(dplyr)
DF1 %>% mutate(Change = change(Before, Now)) -> DF2