Reputation: 367
3I have this function:
nombre_points<-function(typeAction)
{
if(typeAction==1)
{return(4)}
else if (typeAction==2)
{return(3)}
else if (typeAction==3)
{return(2)}
}
And I want to applicate it to each columns of a data frame
df>
ID 1 2 3
XX 0 1 2
YY 1 2 3
EE 2 2 1
ZZ 0 3 4
I want to applicate the above function to this data frame where the input of the
nombre_points
function is the column's number.
So as result I need to get for each row a data frame like this:
df>
ID Result
XX 7
YY 14
EE 16
ZZ 17
In fact for the observation ZZ for example 17=0*4+3*3+4*2
also for the XX observation we have a score :7=0*4+3*1+2*2
I tried to used apply
function :
dd<-apply(df,1,nombre_points)
But it doesn't give the needed result
Upvotes: 0
Views: 48
Reputation: 389335
Update
Since, the values might not be related to column number we can create a named vector or a lookup dataframe to get the corresponding values.
With lookup table :
named_df <- data.frame(col = c(1, 2, 3), value = c(4, 3, 2))
rowSums(df[-1] * named_df$value[col(df[-1])])
#[1] 7 16 16 17
With named vector :
named_vec <- c("1" = 4, "2" = 3, "3" = 2)
rowSums(named_vec[col(df[-1])] * df[-1])
#[1] 7 16 16 17
The logic for both the approach is the same , we match the column number with the name of named_vec
or col
of named_df
and get the corresponding value and then multiply it with the actual value in the dataframe and then take sum of each row using rowSums
.
Original Answer
You could multiply each value in the dataframe with it's column number - 1 to get your desired result. Here, df[-1]
is to ignore the first column (ID
).
df$result <- rowSums(df[-1] * (col(df) - 1))
df
# ID X1 X2 X3 result
#1 XX 0 1 2 5
#2 YY 1 2 3 8
#3 EE 2 2 1 4
#4 ZZ 0 3 4 11
For understanding purposes col(df)
gives
# [,1] [,2] [,3] [,4]
#[1,] 1 2 3 4
#[2,] 1 2 3 4
#[3,] 1 2 3 4
#[4,] 1 2 3 4
Upvotes: 2