Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R add vector content to data frame index

Tags:

dataframe

r

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!

like image 352
Oscar Avatar asked Mar 06 '23 14:03

Oscar


2 Answers

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)
like image 181
Lennyy Avatar answered Mar 17 '23 10:03

Lennyy


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))
like image 44
989 Avatar answered Mar 17 '23 12:03

989