我有以下数据框(标题到期和结果)。
我有以下向量:
index <- c("apple", "kiwi", "banana", "peach", "grape")
苹果= 1,猕猴桃= 2,香蕉= 3,桃= 4,葡萄= 5
我想获得以下输出。
我该如何解决这个问题?
myDf <- structure(list(expiry = 20161212:20161215, fruit = structure(c(4L,
1L, 2L, 3L), .Label = c("2,4", "3,2", "4", "5,3,1"), class = "factor")), .Names = c("expiry",
"fruit"), class = "data.frame", row.names = c(NA, -4L))
index <- c("apple", "kiwi", "banana", "peach", "grape")
答案 0 :(得分:2)
在tidyverse中更具可读性:
library(dplyr)
library(purrr)
df <- data_frame(expiry=c("20161212", "20161213", "20161214", "20161215"),
fruit=c("5,3,1", "2,4", "3,2", 4))
index <- c("apple", "kiwi", "banana", "peach", "grape")
by_row(df, function(x) {
strsplit(x$fruit, ",")[[1]] %>%
as.numeric() %>%
map_chr(~index[.]) %>%
paste0(collapse=",")
}, .collate="cols", .to="fruit_names") %>%
select(expiry, fruit=fruit_names)
## # A tibble: 4 × 2
## expiry fruit
## <chr> <chr>
## 1 20161212 grape,banana,apple
## 2 20161213 kiwi,peach
## 3 20161214 banana,kiwi
## 4 20161215 peach
答案 1 :(得分:1)
您可以使用sapply
,strsplit
和as.numeric
,as.character
来创建变量:
myDf$fruit2 <- sapply(as.character(myDf$fruit), function(x)
paste0(index[as.numeric(strsplit(x, split = ",")[[1]])], collapse = ", "))