azach
azach

Reputation: 99

Rstudio: Replace copy&paste with loop

I'm struggling to automatize this function for df_all. Due to the fact that an example code may be the best way to show what, my goal is here's a simple example for reproduction:

# construct datastructure
loop <- 5
df_one <- as.data.frame(matrix(nrow = loop , ncol = 2))
for(i in 1:loop) {
  a <- 0+i
  b <-  4+i
  df_one[i,1] <- a
  df_one[i,2] <- b
}

df_one
# V1 V2
# 1  1  5
# 2  2  6
# 3  3  7
# 4  4  8
# 5  5  9

#this creates my goal
df_all <- as.data.frame(matrix(nrow = loop, ncol = loop))

for(i in 1:loop) {
  df_all[i,1] <- paste(df_one[i,1], df_one[1,2], sep ="")
  df_all[i,2] <- paste(df_one[i,1], df_one[2,2], sep ="")
  df_all[i,3] <- paste(df_one[i,1], df_one[3,2], sep ="")
  df_all[i,4] <- paste(df_one[i,1], df_one[4,2], sep ="")
  df_all[i,5] <- paste(df_one[i,1], df_one[5,2], sep ="")
}

df_all
# V1 V2 V3 V4 V5
# 1 15 16 17 18 19
# 2 25 26 27 28 29
# 3 35 36 37 38 39
# 4 45 46 47 48 49
# 5 55 56 57 58 59

I want to replace the copy&paste part of the second loop below with another loop, so I can use that for large dataframes:

df_all[i,1] <- paste(df_one[i,1], df_one[1,2], sep ="")
df_all[i,2] <- paste(df_one[i,1], df_one[2,2], sep ="")
...

I hope someone can help me

Upvotes: 0

Views: 48

Answers (2)

see-king_of_knowledge
see-king_of_knowledge

Reputation: 523

You can utilize paste0:

matrix(paste0(df_one$V1, rep(df_one$V2, each = loop)), nrow = loop)

     [,1] [,2] [,3] [,4] [,5]
[1,] "15" "16" "17" "18" "19"
[2,] "25" "26" "27" "28" "29"
[3,] "35" "36" "37" "38" "39"
[4,] "45" "46" "47" "48" "49"
[5,] "55" "56" "57" "58" "59"

Upvotes: 0

K.Hua
K.Hua

Reputation: 799

I think the function outer is what you are looking for.

The output of this function is a matrix, you can then convert it to a dataframe if you want

as.data.frame(outer(df_one[,1], df_one[,2], FUN = paste0))

  V1 V2 V3 V4 V5
1 15 16 17 18 19
2 25 26 27 28 29
3 35 36 37 38 39
4 45 46 47 48 49
5 55 56 57 58 59

Upvotes: 2

Related Questions