Reputation: 1030
I have a df
like this:
COL1 COL2
AA 1122.7 1212
AB 2334.4 3121
AC 3235.0 975
BC 2231.6 520
BD 6456.0 4005
CC 3225.4 9986
min 234.3 60
How can I divide all column values by the value of "min"
row?
I'm trying something like this
df[,] <- lapply(df[,], function(x) x/x[["min"]])
But I receive Subscript out of bounds
Any help would be appreciated
Upvotes: 0
Views: 45
Reputation: 105
You can try sapply, sapply() function does the same job as lapply() function but returns a vector
df/sapply(df,min)
Upvotes: 0
Reputation: 886998
We need sapply
instead of lapply
as lapply
returns a list
by default, while sapply
returns a vector
when there is a single value
newdf <- df1/sapply(df1, min)
Upvotes: 0
Reputation: 39595
Maybe this can help:
#Code
newdf <- df1/apply(df1,2,min)
Output:
COL1 COL2
AA 4.79172 20.200000
AB 38.90667 13.320529
AC 13.80708 16.250000
BC 37.19333 2.219377
BD 27.55442 66.750000
CC 53.75667 42.620572
min 1.00000 1.000000
Or this:
#Index
v <- rownames(df1)
i <- which(v=='min')
#Code 2
newdf <- df1[-i,]/df1[i,,drop=T]
newdf <- rbind(newdf,df1[i,])
Output:
COL1 COL2
AA 4.791720 20.200000
AB 9.963295 52.016667
AC 13.807085 16.250000
BC 9.524541 8.666667
BD 27.554417 66.750000
CC 13.766112 166.433333
min 234.300000 60.000000
Upvotes: 1