我想知道如何想出新的变量"test_array",它是数据类型数组,通过将列"test_1"组合到"test_4"来创建,因为我想用它来进一步计算。
id test_1 test_2 test_3 test_4 test_array
1 10 20 30 40 [10,20,30,40]
2 3 10 20 [ , 3, 10,20]
3 58 98 [58,98, , ]
在此处输入图像描述
这是另一个使用tidyr::nest
按id
嵌套数据的选项。结果是一个新的列data
包含list
tibble
s。
library(tidyverse)
df %>% left_join(df %>%
group_by(id) %>%
nest())
# id test_1 test_2 test_3 test_4 data
#1 1 10 20 30 40 10, 20, 30, 40
#2 2 NA 3 10 20 NA, 3, 10, 20
#3 3 58 98 NA NA 58, 98, NA, NA
样本
df <- read.table(text =
"id test_1 test_2 test_3 test_4
1 10 20 30 40
2 '' 3 10 20
3 58 98 '' ''", header = T)
更新
要计算data
中每个元素的最大值,您可以这样做
library(tidyverse)
df %>%
group_by(id) %>%
nest() %>%
mutate(max = map_dbl(data, ~max(.x, na.rm = T)))
## A tibble: 3 x 3
# id data max
# <int> <list> <dbl>
#1 1 <tibble [1 × 4]> 40.
#2 2 <tibble [1 × 4]> 20.
#3 3 <tibble [1 × 4]> 98.
试试这个例子:
# example data
df1 <- mtcars[1:3, 1:4]
df1$test_array <- lapply(data.frame(t(df1)), as.numeric)
# mpg cyl disp hp test_array
# Mazda RX4 21.0 6 160 110 21, 6, 160, 110
# Mazda RX4 Wag 21.0 6 160 110 21, 6, 160, 110
# Datsun 710 22.8 4 108 93 22.8, 4.0, 108.0, 93.0
使用within
:
within(df, test_array <- paste(test_1, test_2, test_3, test_4, sep=","))
输出:
id test_1 test_2 test_3 test_4 test_array
1 1 10 20 30 40 10,20,30,40
2 2 NA 3 10 20 NA,3,10,20
3 3 58 98 NA NA 58,98,NA,NA