如何有效地结合多列的方法?我想创建一个对象,其中包含以A开头的变量的均值列表和一个单独的对象,该对象具有以C开头的变量的均值列表。理想情况下,我可以使用列号而不是变量名称列号更容易输入。
A1U_sweet A2F_dip A3U_bbq C1U_sweet C2F_dip C3U_bbq
1 2 1 NA NA NA
NA NA NA 4 1 2
2 4 7 NA NA NA
我过去使用过以下功能,但效率很低。我有比这里描述的更多的列。我将此包括在内以澄清我想要做的事情。
average_A<-data.frame((mean(A1U_sweet, na.rm = TRUE)), (mean(A2F_dip, na.rm = TRUE)), (mean(A3U_bbq, na.rm = TRUE)))
average_C<-data.frame((mean(C1U_sweet, na.rm = TRUE)), (mean(C2F_dip, na.rm = TRUE)), (mean(C3U_bbq, na.rm = TRUE)))
答案 0 :(得分:1)
我们可以使用列名的第一个字符split
数据,然后使用colMeans
对每个list
元素执行base R
并保留输出在list
lst <- lapply(split.default(df1, sub("\\d+.*", "", names(df1))), colMeans, na.rm = TRUE)
lst
#$A
# A1U_sweet A2F_dip A3U_bbq
# 1.5 3.0 4.0
#$C
# C1U_sweet C2F_dip C3U_bbq
# 4 1 2
或者使用substr
并在删除列名称的前缀部分后将其保留在单个数据集中
res <- t(sapply(split.default(df1, substr(names(df1), 1, 1)), colMeans, na.rm = TRUE))
colnames(res) <- sub("^..", "", colnames(res))
res
# U_sweet F_dip U_bbq
#A 1.5 3 4
#C 4.0 1 2
或另一个选项是使用tidyverse
,我们gather
将数据mean
加入&#39; long&#39;格式然后按组<{1}}获取
library(dplyr)
library(tidyr)
library(stringr)
df1 %>%
gather(group, value) %>%
group_by(grp = str_sub(group, 1, 1), group) %>%
summarise(value = mean(value, na.rm = TRUE)) %>%
ungroup %>%
select(-grp)
# A tibble: 6 x 2
# group value
# <chr> <dbl>
#1 A1U_sweet 1.50
#2 A2F_dip 3.00
#3 A3U_bbq 4.00
#4 C1U_sweet 4.00
#5 C2F_dip 1.00
#6 C3U_bbq 2.00
df1 <- structure(list(A1U_sweet = c(1L, NA, 2L), A2F_dip = c(2L, NA,
4L), A3U_bbq = c(1L, NA, 7L), C1U_sweet = c(NA, 4L, NA), C2F_dip = c(NA,
1L, NA), C3U_bbq = c(NA, 2L, NA)), .Names = c("A1U_sweet", "A2F_dip",
"A3U_bbq", "C1U_sweet", "C2F_dip", "C3U_bbq"), class = "data.frame",
row.names = c(NA, -3L))