简体   繁体   中英

Treshold values row-wise in a dataframe

Consider an example data frame:

A   B   C   v
5   4   2   3
7   1   3   5
1   2   1   1

I want to set all elements of a row to 1 if the element is bigger or equal than v , and 0 otherwise. The example data frame would result in the following:

A   B   C   v
1   1   0   3
1   0   0   5
1   1   1   1

How can I do this efficiently? The number of columns will be much higher, and I would like a solution that does not require me to specify the names of the columns individually, and will apply it to all of them (except v ) instead.

My solution with a for loop is way too slow.

我们可以创建一个逻辑矩阵并强制转换为二进制

df1[-4] <- +(df1[-4] >= df1$v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM