I would like to add the content of a vector to a data frame. For example, I have a vector like:
1, 2, 1, 1, 2, 4
And a data frame like:
Name1 Name2 Name3 Name4 Name5 Name6
    3     2     2     0     3     1
And I would like to count the numbers that appear in the vector, and add that number to that column index in de data frame, so in this example I would get a data frame like:
Name1 Name2 Name3 Name4 Name5 Name6
    6     4     2     1     3     1
Because there are three 1, two 2, and one 4 in the vector.
I don't know if I have been clear enough, but thanks!
df + replace(vec, 1:6, tabulate(vec, 6))
  Name1 Name2 Name3 Name4 Name5 Name6
1     6     4     2     1     3     1
Ore more generally, with some explanation:
df + replace(vec, 1:dim(df)[2], tabulate(vec, dim(df)[2]))
    #replace values in vec
    #list of values to be replaced: 1:6 (since you have 6 columns)
    #replaced by the occurence of each value in vec (using tabulate with nbins ensures each value between 1 and 6 is in the replacement list, with zeroes for 3, 5 and 6)   
    #finally, add it to df
DATA:
vec <- c(1, 2, 1, 1, 2, 4)
df <- read.table(text = "
                 Name1 Name2 Name3 Name4 Name5 Name6
    3     2     2     0     3     1", h = T)
                        If the column names are like you stated in your question, then something like:
tb <- table(vec)
cols <- paste0("Name", names(tb))
df[cols] <- df[cols] + tb
where vec is your vector and df your data frame.
In case the column names do not matter but the index of the columns then replace cols with
cols <- as.numeric(names(tb))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With