例如:
我有一个数据框架:
a 1 2 3 4 5 6
b 7 8 9 1 2 3
c 4 5 6 7 8 9 我想把它转换成:
a 1 2 3
a 4 5 6
b 7 8 9
b 1 2 3
c 4 5 6
c 7 8 9基本上,每一行我都要第二到第六、第七到第十一、第十一到第十五.变量值将一行移动到第一个变量值是原始行的字母的位置。
我该怎么办?我试着使用here (),但这里不是这样的。我只是一个在R的初学者,并将感谢任何帮助。谢谢
发布于 2020-08-02 19:13:23
这将按3列分组;只需将%/% 3更改为%/% 5,以对应不同的列数。(这假定每个分组中有相同数量的列。)
out <- do.call(rbind, lapply(split.default(dat[,-1], (seq_along(dat[,-1])-1) %/% 3),
function(a) cbind(dat[,1,drop=FALSE], unname(a))))
out
# V1 1 2 3
# 0.1 a 1 2 3
# 0.2 b 7 8 9
# 0.3 c 4 5 6
# 1.1 a 4 5 6
# 1.2 b 1 2 3
# 1.3 c 7 8 9我们可以把它清理一下
row.names(out) <- NULL
out[order(out[,1]),]
# V1 1 2 3
# 1 a 1 2 3
# 4 a 4 5 6
# 2 b 7 8 9
# 5 b 1 2 3
# 3 c 4 5 6
# 6 c 7 8 9发布于 2020-08-02 19:17:50
用tidyverse
硬代码版本
使用select隔离前4列(三个值和键)
rbind和select最后3列和键rbind组合的列重命名为与上面步骤1中的select df相同的名称。按键排列的
arrangedf %>% select(1:4) %>% rbind(df %>% select(1,"v1“= 5,"v2”= 6," v3“=7) %>%安排( key )#key v1 v2 v3#1 a 1 2 3#2 a 4 5 6#3 b 7 8 9 4 b 1 2 3 c 4 5 6 6 c 7 8
编辑通用的(有点干草)
样本df
set.seed(42)
df_2 <- tibble(
bug = letters,
col1 = sample(1:26),
col2 = sample(1:26),
col3 = sample(1:26),
col4 = sample(1:26),
col5 = sample(1:26),
col6 = sample(1:26),
col7 = sample(1:26),
col8 = sample(1:26),
col9 = sample(1:26),
col10 = sample(1:26),
col11 = sample(1:26),
col12 = sample(1:26),
col13 = sample(1:26),
col14 = sample(1:26),
col15 = sample(1:26)
)满足广义方法的函数
create_rowgroups.f <- function(df, key, groupsize){
if( !(key %in% colnames(df)) ){
print(paste(key, "is expected to be a column in df"))
stop()
}
if( (ncol(df)-1) %% groupsize != 0 ){
print("Function requires groups to fit all variable columns with the exception of the key")
stop()
}
fnames = colnames(df[ , 1: (groupsize + 1) ])
df_2 <- bind_rows(lapply(
1:(ncol(df)/groupsize),
function(df, groupsize, key, fnames, index){
pos1 = (index * groupsize) - groupsize + 2
pos2 = (index * groupsize) + 1
tempdf <- df %>% select(!!key, !!pos1:!!pos2)
colnames(tempdf) = fnames
return(tempdf)
},
df = df,
key = key,
fnames = fnames,
groupsize = groupsize
))
df_2 <- df_2 %>% arrange(across(.cols = key))
return(df_2)
}这是许多围绕着简单的lapply行的代码,以帮助OP使用UDF,create_rowgroups.f
发布于 2020-08-02 21:15:07
如果所显示的数据是所显示的,则可以通过简单的列子设置来完成这一任务,并且在设置列名后对数据集进行rbind设置。
library(dplyr)
rbind(df1[1:4], setNames(df1[c(1, 5:7)], names(df1)[1:4])) %>%
arrange(1)如果有许多列,一个更容易理解的自动方法是seq。循环遍历索引序列、列子集、rbind在do.call中,因为我们要通过循环来创建list
out <- cbind(df1[1], do.call(rbind, lapply(seq(2, ncol(df1), by = 3),
function(i) setNames(df1[i:(i+2)], paste0("v", 2:4)))))
out[order(out$v1),]数据
df1 <- structure(list(v1 = c("a", "b", "c"), v2 = c(1L, 7L, 4L), v3 = c(2L,
8L, 5L), v4 = c(3L, 9L, 6L), v5 = c(4L, 1L, 7L), v6 = c(5L, 2L,
8L), v7 = c(6L, 3L, 9L)), class = "data.frame", row.names = c(NA,
-3L))https://stackoverflow.com/questions/63219919
复制相似问题