给向量中的字符串值一个自动索引
Give string values in vector an auto index
我有两个向量:
names_of_p <- c("John", "Adam", "James", "Robert")
speeds <- c("Slow", "Fast", "Average", "Slow")
我需要向最慢的人展示,我用 if's 和 if else's 做到了,但我想知道是否有更简单的方法来做到这一点,比如 auto give "Slow" = 1 , "Average" = 2 and很快。换句话说,为它们附加价值。
最后它应该是像
这样的向量
names_speeds <- c(names_of_p, speed)
然后我可以比较人,看看谁更快。
首先将 names
分配给向量 speeds
然后你得到一个命名的向量。
之后你可以使用 which
:
names(speeds) <- names
which(speeds=="Slow")
John Robert
1 4
您可以将 speeds
转换为有序因子,这将保留标签,同时还创建基础数字表示:
names_of_p <- c("John", "Adam", "James", "Robert")
speeds <- c("Slow", "Fast", "Average", "Slow")
speeds <- factor(speeds, levels = c('Slow', 'Average', 'Fast'), ordered = T)
names_of_p[order(speeds)]
[1] "John" "Robert" "James" "Adam"
names_of_p[as.numeric(speeds) < 3]
[1] "John" "James" "Robert"
将数据存储在数据框中而不是单独的向量中也可能是个好主意:
library(tidyverse)
df <- data.frame(
names_of_p = names_of_p,
speeds = factor(speeds, levels = c('Slow', 'Average', 'Fast'), ordered = T)
)
df %>%
arrange(speeds)
names_of_p speeds
<chr> <ord>
1 John Slow
2 Robert Slow
3 James Average
4 Adam Fast
df %>%
filter(as.numeric(speeds) < 3)
names_of_p speeds
<chr> <ord>
1 John Slow
2 James Average
3 Robert Slow
我有两个向量:
names_of_p <- c("John", "Adam", "James", "Robert")
speeds <- c("Slow", "Fast", "Average", "Slow")
我需要向最慢的人展示,我用 if's 和 if else's 做到了,但我想知道是否有更简单的方法来做到这一点,比如 auto give "Slow" = 1 , "Average" = 2 and很快。换句话说,为它们附加价值。 最后它应该是像
这样的向量names_speeds <- c(names_of_p, speed)
然后我可以比较人,看看谁更快。
首先将 names
分配给向量 speeds
然后你得到一个命名的向量。
之后你可以使用 which
:
names(speeds) <- names
which(speeds=="Slow")
John Robert
1 4
您可以将 speeds
转换为有序因子,这将保留标签,同时还创建基础数字表示:
names_of_p <- c("John", "Adam", "James", "Robert")
speeds <- c("Slow", "Fast", "Average", "Slow")
speeds <- factor(speeds, levels = c('Slow', 'Average', 'Fast'), ordered = T)
names_of_p[order(speeds)]
[1] "John" "Robert" "James" "Adam"
names_of_p[as.numeric(speeds) < 3]
[1] "John" "James" "Robert"
将数据存储在数据框中而不是单独的向量中也可能是个好主意:
library(tidyverse)
df <- data.frame(
names_of_p = names_of_p,
speeds = factor(speeds, levels = c('Slow', 'Average', 'Fast'), ordered = T)
)
df %>%
arrange(speeds)
names_of_p speeds
<chr> <ord>
1 John Slow
2 Robert Slow
3 James Average
4 Adam Fast
df %>%
filter(as.numeric(speeds) < 3)
names_of_p speeds
<chr> <ord>
1 John Slow
2 James Average
3 Robert Slow