Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneously subsetting and operating on a specific column of a data frame

Tags:

r

subset

Let's say I have data.frame df

df<-data.frame(a=1:5,b=101:105,c=201:205)

Can I call a subset of this data while simultaneously performing some kind of modification (e.g., arithmetic) to one of the columns (or rows) on the fly?

For example, if I want to return the first and second column of df but return the log of column 1 values. Is there some notation to modify df[,1:2] to produce the following all on the fly?:

            a   b
>1  0.0000000 101
>2  0.6931472 102
>3  1.0986123 103
>4  1.3862944 104
>5  1.6094379 105
like image 615
theforestecologist Avatar asked Aug 07 '15 18:08

theforestecologist


1 Answers

This is a good example for within()

within(df[1:2], a <- log(a))
#           a   b
# 1 0.0000000 101
# 2 0.6931472 102
# 3 1.0986123 103
# 4 1.3862944 104
# 5 1.6094379 105

Or if you prefer not to have <- in the call, you can use brackets

within(df[1:2], { a = log(a) })
like image 139
Rich Scriven Avatar answered Oct 13 '22 20:10

Rich Scriven