重复列 a 到新行
Repeated columns a into new row
我在 a 列中重复了值,我希望这些值成为包含 b 列信息的新行。
我已经尝试了收集和传播的 tidyr 函数
library("tidyr")
rearrangeddf<-spread(df,a,b)
#Input
a=c("A","A","A","A","A","B","B","B","B","B")
b=c(1,2,3,4,5,11,12,13214634,14,15432)
df=data.frame(a,b)
#Output
x=c("A",1,2,3,4,5)
y=c("B",11,12,13214634,14,1543)
rearrangeddf=rbind(x,y)
Error: Each row of output must be identified by a unique combination of keys.
Keys are shared for 10 rows:
* 1, 2, 3, 4, 5
* 6, 7, 8, 9, 10
Do you need to create unique ID with tibble::rowid_to_column()?
Call rlang::last_error()
to see a backtrace
您可以使用
aggregate(b~a, df, c)
a b.1 b.2 b.3 b.4 b.5
1 A 1 2 3 4 5
2 B 11 12 13214634 14 15432
不是答案的一部分
不要使用 c=c("A",1,2,3,4,5)
,因为这会覆盖 c()
函数。看这里:
c=c("A",1,2,3,4,5)
aggregate(b~a, df, c)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'FUN' of mode 'function' was not found
你可以这样做:
df <- data.frame(a=c("A","A","A","A","A","B","B","B","B","B"),
b=c(1,2,3,4,5,11,12,13214634,14,15432))
t(unstack(df, b ~ a))
# > t(unstack(df, b ~ a))
# [,1] [,2] [,3] [,4] [,5]
# A 1 2 3 4 5
# B 11 12 13214634 14 15432
感谢@Sotos,这很完美
library(dplyr)
library(tidyr)
df %>%group_by(a) %>% mutate(new = row_number()) %>% spread(new, b)
我在 a 列中重复了值,我希望这些值成为包含 b 列信息的新行。
我已经尝试了收集和传播的 tidyr 函数
library("tidyr")
rearrangeddf<-spread(df,a,b)
#Input
a=c("A","A","A","A","A","B","B","B","B","B")
b=c(1,2,3,4,5,11,12,13214634,14,15432)
df=data.frame(a,b)
#Output
x=c("A",1,2,3,4,5)
y=c("B",11,12,13214634,14,1543)
rearrangeddf=rbind(x,y)
Error: Each row of output must be identified by a unique combination of keys. Keys are shared for 10 rows: * 1, 2, 3, 4, 5 * 6, 7, 8, 9, 10 Do you need to create unique ID with tibble::rowid_to_column()? Call
rlang::last_error()
to see a backtrace
您可以使用
aggregate(b~a, df, c)
a b.1 b.2 b.3 b.4 b.5
1 A 1 2 3 4 5
2 B 11 12 13214634 14 15432
不是答案的一部分
不要使用 c=c("A",1,2,3,4,5)
,因为这会覆盖 c()
函数。看这里:
c=c("A",1,2,3,4,5)
aggregate(b~a, df, c)
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'FUN' of mode 'function' was not found
你可以这样做:
df <- data.frame(a=c("A","A","A","A","A","B","B","B","B","B"),
b=c(1,2,3,4,5,11,12,13214634,14,15432))
t(unstack(df, b ~ a))
# > t(unstack(df, b ~ a))
# [,1] [,2] [,3] [,4] [,5]
# A 1 2 3 4 5
# B 11 12 13214634 14 15432
感谢@Sotos,这很完美
library(dplyr)
library(tidyr)
df %>%group_by(a) %>% mutate(new = row_number()) %>% spread(new, b)