[英]How to replace numeric values in a dataframe by categorical labels in R?
How to replace numeric values of this dataframe:如何替换此数据框的数值:
df <- data.frame(num = 1:10, num2=-8:1, num3=2:11)
df <- as.matrix(df)
into cut labels?成切割标签?
df_categ <- cut(df, breaks = c(-Inf, 2, 4, Inf), labels=c("DOWN", "NORM", "UP"))
cut gives a list. cut 给出了一个列表。 But I need to substitute my numeric elements in the original df但是我需要在原始 df 中替换我的数字元素
We could use []
to convert it to original attributes我们可以使用[]
将其转换为原始属性
df[] <- as.character(df_categ)
Instead of converting the 'df' to a matrix
, we could use the original data.frame我们可以使用原始 data.frame,而不是将 'df' 转换为matrix
library(dplyr)
df <- df %>%
mutate(across(everything(), cut,
breaks = c(-Inf, 2, 4, Inf), labels = c("DOWN", "NORM", "UP")))
df
num num2 num3
1 DOWN DOWN DOWN
2 DOWN DOWN NORM
3 NORM DOWN NORM
4 NORM DOWN UP
5 UP DOWN UP
6 UP DOWN UP
7 UP DOWN UP
8 UP DOWN UP
9 UP DOWN UP
10 UP DOWN UP
Or use lapply
from base R
或者使用base R
lapply
df[] <- lapply(df, cut, breaks = c(-Inf, 2, 4, Inf),
labels = c("DOWN", "NORM", "UP"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.