Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 基于字符串序列将字符串向量转换为数字向量_R - Fatal编程技术网

R 基于字符串序列将字符串向量转换为数字向量

R 基于字符串序列将字符串向量转换为数字向量,r,R,我有一个向量,像 A <- c("A","A","B","B", "C","C","C", "D") 这可能吗?试试: A <- c("A","A","B","B", "C","C","C", "D") as.numeric(factor(A)) [1] 1 1 2 2 3 3 3 4 或 如果第一个序列是您想要的,您可能会发现plyr::mapvalues很有趣,以防您在某些时候遇到更复杂的情况。比如说, library(plyr) mapvalues(A, from=uniq

我有一个向量,像

A <- c("A","A","B","B", "C","C","C", "D")
这可能吗?

试试:

A <- c("A","A","B","B", "C","C","C", "D")
as.numeric(factor(A))
[1] 1 1 2 2 3 3 3 4

如果第一个序列是您想要的,您可能会发现
plyr::mapvalues
很有趣,以防您在某些时候遇到更复杂的情况。比如说,

library(plyr)
mapvalues(A, from=unique(A), to=1:4)
[1] "1" "1" "2" "2" "3" "3" "3" "4"

当你需要更多的控制时,这很方便。例如,您可以轻松地将其他输出作为
提供给
参数,例如
month.name[1:4]

你期望的答案是什么。“A”和“B”的长度不同,向量B是我的答案。我有一个A,想把它变成BB,A有8个元素,B有9个向量,B不是“基于序列”的,是
split(seq(A),A)
你在找什么?这已经很接近了。我的包需要一个向量根据因子级别为图形着色:我需要告诉它新因子级别从何处开始(因此使用1:2,3:4,5:7,8语法)。我看它是否能与这些建议配合使用。请注意:如果您需要一个新因子级别开始的指示器,假设您的数据集是按因子级别排序的,您可以尝试类似于
diff(as.numeric(factor(a)))
的方法。不过,大多数软件包应该能够理解正常因素。
labels(factor(A))
[1] "1" "2" "3" "4" "5" "6" "7" "8"
1:length(A)
[1] 1 2 3 4 5 6 7 8
library(plyr)
mapvalues(A, from=unique(A), to=1:4)
[1] "1" "1" "2" "2" "3" "3" "3" "4"