Reputation: 17388
I have this:
df1 <- data.frame(A = c('a', 'b', 'c'), B = c('d', 'e', 'c'))
and would like to transform it to this:
A B
1 A:a B:d
2 A:b B:e
3 A:c B:c
My current not working miserable 'loop' attempt (using apply version preferred) is this:
for (row in 1:nrow(df1)) {
for (col in 1:ncol(df1)) {
levels(colnames(df1)[col])[levels(colnames(df1)[col]) == df1[row, col]] <- paste0(colnames(df1)[col], ":", df1[row, col])
}
}
Upvotes: 1
Views: 168
Reputation: 39858
In the case you want to do it using tidyverse
:
df1 %>%
rowid_to_column() %>% #Creating row IDs
gather(var, val, -rowid) %>% #Transforming the data from wide to long
mutate(temp = paste(var, val, sep = ":")) %>% #Combining the column names with the level of factors
select(-val) %>%
spread(var, temp) %>% #Transforming the data back to wide format
select(-rowid) #Deleting the redundant variable
A B
1 A:a B:d
2 A:b B:e
3 A:c B:c
Upvotes: 1
Reputation: 388807
An option using lapply
where we go through each column and paste
the name of the column along with column values.
df1[] <- lapply(seq_along(df1), function(x) paste0(names(df1)[x],":", df1[,x]))
df1
# A B
#1 A:a B:d
#2 A:b B:e
#3 A:c B:c
Upvotes: 3
Reputation: 37879
One way with mapply
:
data.frame(mapply(function(x, y) paste0(y, ':', x), df1, c('A', 'B')))
# A B
#1 A:a B:d
#2 A:b B:e
#3 A:c B:c
Or you could do:
data.frame(A = paste0('A:', df1$A),
B = paste0('B:', df1$B))
But I would go for the first option if you have multiple columns that you would like to use this logic on.
Upvotes: 4