Home > Mobile >  Add elements from vector to every nth column of dataframe in R
Add elements from vector to every nth column of dataframe in R

Time:01-16

I have the following vector:

samples <- c("bl", "ra", "ye", "gp", "dk")

which I would like to add to the dataframe

df <- data.frame(Country = "FR", Name = "Jean", A="",B="",C="",D="",E="",F="",G="",H="",I="",J="",L="",M="",N="",O="",P="",Q="",R="",S="",T="",U="",V="",W="ok",X="ok",Y="ok",Z="ok",A1="ok",B1="ok")

and give the output

  Country Name   A  B   C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T ....
1      FR Jean   bl           ra          ye          gp          dk

The aim:

  • Place elements within the vector into the dataframe that already contains some values.
  • The first element has to be in column 3
  • Subsequent elements have to be in every 5th column from the first element i.e columns 7, 11, 15, 19, ... (4i-1)
  • A for loop that automatically adds the elements every 5th column from the first element. Depending on the situation, I may have a much longer vector than what I specified. It would be tedious to assign each element to the column names individually.

CodePudding user response:

There is no need of a loop. You can directly assign samples to the corresponding columns.

df[, seq_along(samples) * 4 - 1   2] <- samples

df
#   Country Name A B  C D E F  G H I J  L M N O  P Q R S  T U V  W  X  Y  Z A1 B1
# 1      FR Jean     bl       ra       ye       gp       dk     ok ok ok ok ok ok

CodePudding user response:

First define a target_pos vector containing the position of your target columns, then iterate over the vector to append samples to your df.

Note there's some differences between your input df and your desired output. For example you don't have column K in your df but you have that in your desired output.

target_pos <- seq(5, 5*length(samples) - 4, 4)

for (i in 1:length(target_pos)) df[, target_pos[i]] <- samples[i]

df
#>   Country Name A B  C D E F  G H I J  L M N O  P Q R S  T U V  W  X  Y  Z A1 B1
#> 1      FR Jean     bl       ra       ye       gp       dk     ok ok ok ok ok ok

Data

df<-data.frame(Country = "FR", Name = "Jean", A="",B="",C="",D="",E="",F="",G="",H="",I="",J="",L="",M="",N="",O="",P="",Q="",R="",S="",T="",U="",V="",W="ok",X="ok",Y="ok",Z="ok",A1="ok",B1="ok")

samples=c("bl","ra","ye","gp","dk")
  • Related