R 将定界整数映射到定界字符串
R map delimited integers to delimited strings
输入
我有以下数据框(headers 过期和结果)。
我有以下向量:
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")
您可以使用 sapply
、strsplit
和 as.numeric
、as.character
来创建您的变量:
myDf$fruit2 <- sapply(as.character(myDf$fruit), function(x)
paste0(index[as.numeric(strsplit(x, split = ",")[[1]])], collapse = ", "))
在 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
输入
我有以下数据框(headers 过期和结果)。
我有以下向量:
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")
您可以使用 sapply
、strsplit
和 as.numeric
、as.character
来创建您的变量:
myDf$fruit2 <- sapply(as.character(myDf$fruit), function(x)
paste0(index[as.numeric(strsplit(x, split = ",")[[1]])], collapse = ", "))
在 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