Reputation: 1
I'm trying to create a data frame conditional on another frame on every single element.
For example:
c0 <- c(0.1,0.2,0.5,.1)
c1 <- c(0.1,0.2,0.5,.1)
c2 <- c(0.1,0.2,0.5,.1)
c3 <- c(0.1,0.2,0.5,.1)
c4 <- c(0.1,0.2,0.5,.1)
df <- data.frame(c0,c1,c2,c3,c4)
colnames(df)<-c("A","B","C","D","E")
rownames(df)<-c("A","B","C","D")
This will give me a data frame like this:
> df
A B C D E
A 0.1 0.1 0.1 0.1 0.1
B 0.2 0.2 0.2 0.2 0.2
C 0.5 0.5 0.5 0.5 0.5
D 0.1 0.1 0.1 0.1 0.1
Now I want to find if any element is greater than 0.5 if else replace with 0 in a new dataframe:
> df.Indicator <- as.data.frame(lapply(as.matrix(df),function(x)
+ ifelse(x>=0.50,1,0)))
> df.Indicator
X0 X0.1 X1 X0.2 X0.3 X0.4 X1.1 X0.5 X0.6 X0.7 X1.2 X0.8 X0.9 X0.10 X1.3 X0.11 X0.12 X0.13 X1.4 X0.14
1 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0
I would like to get back a data-frame with indicators on same mxn like this
A B C D E
A 0 0 0 0 0
B 0 0 0 0 0
C 1 1 1 1 1
D 0 0 0 0 0
This is a simple example but eventually I would like to establish more conditions.
Thank you!
Upvotes: 0
Views: 56
Reputation: 1
Thank you all. It was actually the as.matrix
statement now it works as desired, without that:
df.Indicator <- as.data.frame(lapply(df,function(x)
ifelse(x>=0.50,1,0)))
> df.Indicator
A B C D E
1 0 0 0 0 0
2 0 0 0 0 0
3 1 1 1 1 1
4 0 0 0 0 0
Upvotes: 0
Reputation: 323226
Data in put
c0 <- c(0.1,0.2,0.5,.1)
c1 <- c(0.1,0.2,0.5,.1)
c2 <- c(0.1,0.2,0.5,.1)
c3 <- c(0.1,0.2,0.5,.1)
c4 <- c(0.1,0.2,0.5,.1)
df <- data.frame(c0,c1,c2,c3,c4)
colnames(df)<-c("A","B","C","D","E")
rownames(df)<-c("A","B","C","D")
A=data.frame(df>=0.5)
data.frame(lapply(A, as.numeric), stringsAsFactors=FALSE)
A B C D E
1 0 0 0 0 0
2 0 0 0 0 0
3 1 1 1 1 1
4 0 0 0 0 0
Upvotes: 0
Reputation: 39154
The replacement you need does not require lapply
or a function. Try the following code.
df[df >= 0.5] <- 1
df[df != 1] <- 0
Or as suggested by others. Use the following code.
df <- (df >= 0.5) * 1
If you really want to use apply
family function, here is a modification of your original code. Use apply
, not lapply
.
df <- as.data.frame(apply(df, 2, function(x) ifelse(x >= 0.5, 1, 0)))
Here is another solution from the dplyr
package.
library(dplyr)
df <- df %>% mutate_all(funs(ifelse(. >= 0.5, 1, 0)))
Upvotes: 1