Hello I would like to establish a min value (0.3) in my dat
dataframe:
col1 col2 col3 col4
0 0.2 0.8 1
0.2 0 0.7 2.1
13.2 12.1 1.58 0
My expected output:
col1 col2 col3 col4
0.3 0.3 0.8 1
0.3 0.3 0.7 2.1
13.2 12.1 1.58 0.3
Cheers!
You can use lapply
to do this
dat[] <- lapply(dat, function(x) ifelse(x<0.3, 0.3, x))
> dat
col1 col2 col3 col4
1 0.3 0.3 0.80 1.0
2 0.3 0.3 0.70 2.1
3 13.2 12.1 1.58 0.3
By using dat[]
instead of only dat
you can keep the class and structure of the existing data.frame. Otherwise, dat
would be a list, since lapply
returns a list.
In case you do have other columns that contain factors
or character
entries, you can still use lapply
and specify which columns you want to be changed. If you had the following data.frame:
> dat
col1 col2 col3 col4 id
1 0.0 0.2 0.80 1.0 a
2 0.2 0.0 0.70 2.1 b
3 13.2 12.1 1.58 0.0 c
You can use lapply
as follows:
> dat[1:4] <- lapply(dat[1:4], function(x) ifelse(x<0.3, 0.3, x)) #only columns 1:4 will be changed
> dat #the id column is as it was and you still have a data.frame
col1 col2 col3 col4 id
1 0.3 0.3 0.80 1.0 a
2 0.3 0.3 0.70 2.1 b
3 13.2 12.1 1.58 0.3 c