R: Create binary data from a data frame

时间秒杀一切 提交于 2019-12-08 11:31:28

问题


i need some advise for the following problem:

I have a dataframe with two columns, one containing the date, the other the frequency of a an event. Now i want to add a third column to this dataframe, wich should contain some binary data: 1 for days with a frequency of 100 and higher, 0 for the lower ones.

Has anyone an idea how to do this in a smart way (i'm affraid of writing it by hand;-)? Thanks for your answer in advance!


回答1:


df$freq.gt.100 = as.integer(df$freq >= 100)

The bit inside brackets evaluates to TRUE or FALSE which can be converted to 1 or 0 via as.integer.

There's nothing to be "afraid" of: you can test the right-hand side of the expression on its own to check it works and only when you are happy with this do you add it as a new column to the original data.

EDIT: didn't see the above answer as I was creating this one and had a call to take!




回答2:


data$newcol = as.integer(data$freq >= 100)

alternatively

data$newcol = ifelse(data$freq >= 100, 1, 0)

alternatively

data$newcal = 0
data$newcol[data$freq >= 100] = 1


来源:https://stackoverflow.com/questions/20992904/r-create-binary-data-from-a-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!