Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a logical vector from data frame

Tags:

dataframe

r

I have a data frame called y

dput(y)
structure(list(val1 = c(25L, 615L, 30L, 76L, 97L, 211L, 0L, 40L, 
10L, 10L), val2 = c(101L, 286L, 124L, 77L, 176L, 120L, 0L, 8L, 
56L, 49L), val3 = c(157L, 454L, 106L, 242L, 144L, 31L, 0L, 40L, 
45L, 57L)), .Names = c("val1", "val2", "val3"), row.names = c(NA, 
10L), class = "data.frame")

I would like to be able to look at val1 and val2 columns and if val1>10, replace the value with TRUE else FALSE and look at val2 and if val2<5, replace the value with TRUE else FALSE

I can use subset function to pick them but rather than using subset, I like to replace values with TRUE or FALSE, any ideas how I would do this?

like image 980
user1471980 Avatar asked Feb 02 '13 19:02

user1471980


People also ask

How do I turn a data frame into a vector?

For the Conversion of dataframe into a vector, we can simply pass the dataframe column name as [[index]]. Approach: We are taking a column in the dataframe and passing it into another variable by the selection method. Selection method can be defined as choosing a column from a data frame using ” [[]]”.

How do you define a logical vector in R?

A logical vector is a vector that only contains TRUE and FALSE values. In R, true values are designated with TRUE, and false values with FALSE. When you index a vector with a logical vector, R will return values of the vector for which the indexing vector is TRUE.

Is a Dataframe a vector?

A data frame is a tabular data structure, consisting of rows and columns and implemented as a list. The columns of a data frame can consist of different data types but each column must be a single data type [like a vector].


1 Answers

Just use boolean operators:

y$val1 > 10 | (y$val1 <=10 & y$val2<5)
# [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
like image 50
nograpes Avatar answered Nov 05 '22 21:11

nograpes