Reputation: 405
I have data frame like this:
df<-data.frame("ID"=c("1","2","3"),"A"=c("A01","A02","A03"),"B"=c("B01","B02","B03"),"C"=c("C01","C02","C03"))
I'm trying to get it in this format without headings but I couldn't:
1
A01,B01,CO1
2
A02,B02,C02
3
A03,B03,C03
This means that the for each ID I should have a new line with the values related to the ID ( a combined values of column 2:4) and they should be separated by a comma. I tried a kable package but I failed to do it can you please help me ?
Upvotes: 0
Views: 56
Reputation: 19097
I'll first create an artificial column ABC
which has A
, B
and C
pasted together with ,
as the delimiter. Then use pivot_longer
to transform the structure to your desired output.
Just ignore colnames(df2) <- NULL
if you would like to have column name in your output.
library(tidyverse)
df2 <- df %>% rowwise() %>%
mutate(ABC = paste(c_across(A:C), collapse = ",")) %>%
select(ID, ABC) %>%
pivot_longer(everything(), names_to = NULL) %>%
as.data.frame()
colnames(df2) <- NULL
df2
1 1
2 A01,B01,C01
3 2
4 A02,B02,C02
5 3
6 A03,B03,C03
Upvotes: 1
Reputation: 11046
Try this
df2 <- data.frame(chars=paste0(apply(df[, 2:3], 1, paste0, sep=",", collapse=""), df[, 4]))
df2
# chars
# 1 A01,B01,C01
# 2 A02,B02,C02
# 3 A03,B03,C03
Upvotes: 0