HI everyone i have 3 vectors:
v1 = c(32,60,20)
v2 = c(60,10,40)
v3 = c(90,45,15)
i want to put them into DataFrame as shown in the screenshot below where: low for value less than 30 average for values more than 30 and less 50 High for value more than 50.
the DataFrame should be like this:
v1 : v2 : v3
low:
average:
High:
CodePudding user response:
This isn't what you asked for but in my opinion it is a more sensible way of coding your data (long format).
#### Library ####
library(tidyverse)
#### Create Vars ####
v1 = c(30,60,20)
v2 = c(40,10,30)
v3 = c(90,20,10)
#### Make Data Frame ####
df <- data.frame(v1,v2,v3)
df_fix <- df %>%
pivot_longer(cols = everything(),
names_to = "Variable",
values_to = "Score") %>%
mutate(Variable_Type = ifelse(Score < 30,
"Low",
ifelse(Score > 50,
"High",
"Average"))) %>%
select(-Variable)
df_fix
Which gives you this cleaner column by variable format:
# A tibble: 9 × 2
Score Variable_Type
<dbl> <chr>
1 30 Average
2 40 Average
3 90 High
4 60 High
5 10 Low
6 20 Low
7 20 Low
8 30 Average
9 10 Low
And if you want to leave the variable names in place by row:
df_row <- df %>%
pivot_longer(cols = everything(),
names_to = "Variable",
values_to = "Score") %>%
mutate(Variable_Type = ifelse(Score < 30,
"Low",
ifelse(Score > 50,
"High",
"Average")))
df_row
Which looks like this:
# A tibble: 9 × 3
Variable Score Variable_Type
<chr> <dbl> <chr>
1 v1 30 Average
2 v2 40 Average
3 v3 90 High
4 v1 60 High
5 v2 10 Low
6 v3 20 Low
7 v1 20 Low
8 v2 30 Average
9 v3 10 Low
CodePudding user response:
Maybe you can use cut
to split the vectors in the classes Low, Average and High. With table
you can get the counts per class.
v1 <- c(32,60,20)
v2 <- c(60,10,40)
v3 <- c(90,45,15)
. <- lapply(mget(c("v1", "v2", "v3")), cut, c(-Inf,30,50,Inf), c("Low", "Average", "High"))
sapply(., table)
# v1 v2 v3
#Low 1 1 1
#Average 1 1 1
#High 1 1 1