Reputation: 27
For example I have a column:
x <- c(-0.5, 1.1, 6.0, 4.5, 0.1, -0.2)
I want to add a new column where each value is assigned with a 3 percentage group For example :
So I will have a new column: c(-3, 3, 9, 6, 3, -3)
Upvotes: 1
Views: 231
Reputation: 389325
You can use findInterval
or cut
for this
x <- c(-0.5, 1.1, 6.0, 4.5, 0.1, -0.2)
brks <- seq(-3, 9, 3)
lbls <- c(-3,3,6,9)
lbls[findInterval(x, brks)]
#[1] -3 3 9 6 3 -3
Or as mentioned by @StupidWolf using cut
cut(x, breaks=brks,right=FALSE, labels=lbls)
Upvotes: 2
Reputation: 5798
Base R solution:
# Define the value using the ranges:
num_frame$perc_group <- ifelse(num_frame$num_vec < 0 & num_frame$num_vec >= -3, -3,
ifelse(num_frame$num_vec == 0, 0,
ifelse(num_frame$num_vec > 0 & num_frame$num_vec <= 3, 3, 6)))
Data:
num_frame <- structure(list(num_vec = c(-0.5, 1.1, 6, 4.5, 0.1, -0.2)),
class = "data.frame",
row.names = c(NA, -6L))
Upvotes: 0