Hej,
This might have been reviewed before, plus my R skills are getting rusty, but I am trying to generate a new dataframe, where rownames will be generated from strings and effectif / sequence number from a two columns data frame.
To make more sense I have a dataframe looking like :
IND Effect
A 3
B 2
C 4
read.table(text = "IND Effect
A 3
B 2
C 4", h = T)
And I want something like
IND
A_1
A_2
A_3
B_1
B_2
C_1
C_2
C_3
C_4
on a new data frame. I tryed :
new = mapply(function(x, y) paste0(rep(x, y), collapse = "_"), IND , Effect)
but doesn't work as I would like....
CodePudding user response:
You may nee the help of the seq_len()
function:
df <- data.frame(ind = c("A", "B", "C"),
effect = c(3, 2, 4))
paste(rep(df$ind, df$effect),
unlist(sapply(df$effect, seq_len)),
sep = "_")
[1] "A_1" "A_2" "A_3" "B_1" "B_2" "C_1" "C_2" "C_3" "C_4"
CodePudding user response:
with mapply
:
m <- mapply(paste, df$ind, sapply(df$effect, seq), sep = "_")
output
unlist(m)
# A1 A2 A3 B1 B2 C1 C2 C3 C4
#"A_1" "A_2" "A_3" "B_1" "B_2" "C_1" "C_2" "C_3" "C_4"
#or, as a data.frame object:
data.frame(new = unname(unlist(m)))
# new
#1 A_1
#2 A_2
#3 A_3
#4 B_1
#5 B_2
#6 C_1
#7 C_2
#8 C_3
#9 C_4
data
df <- data.frame(ind = c("A", "B", "C"),
effect = c(3, 2, 4))