Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.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,我有一个变量,它由三个数字组成,用“.”分隔,其中前两个数字是ID,最后一个是代表号。例如,在“3.4.1”中,ID为“3.4”,代表为“1”。我想分割这些数字,只保留“ID”数字作为新变量。虽然我能得到我想要的,但我相信一定有一个更简单的方法来解决这个问题。以下是一个玩具示例: plant<-c("2.3.1","2.3.2","1.2.1","1.2.2","12.3.1","12.3.2") height<-c(2.3,2.1,2.5,2.6,3,2.9) d<-data

我有一个变量,它由三个数字组成,用“.”分隔,其中前两个数字是ID,最后一个是代表号。例如,在“3.4.1”中,ID为“3.4”,代表为“1”。我想分割这些数字,只保留“ID”数字作为新变量。虽然我能得到我想要的,但我相信一定有一个更简单的方法来解决这个问题。以下是一个玩具示例:

plant<-c("2.3.1","2.3.2","1.2.1","1.2.2","12.3.1","12.3.2")
height<-c(2.3,2.1,2.5,2.6,3,2.9)
d<-data.frame(plant,height)
d$ID<-paste(lapply(strsplit(as.character(d$plant),"[.]"), `[[`, 1),".",lapply(strsplit(as.character(d$plant),"[.]"), `[[`, 2), sep = "")

plant我们可以使用
sub
匹配
(转义点
\.
,因为它是一个元字符),后跟一个或多个非点字符(
[^.]+
),直到字符串的末尾,并用
替换它


成功了。为什么不在第二个示例中转义点?@Cba它在
[]
中,不作为元字符
读取
d$ID <- sub("\\.[^.]+$", "", d$plant)
d$ID
#[1] "2.3"  "2.3"  "1.2"  "1.2"  "12.3" "12.3"
sub("[^.]+$", "", d$plant)
#[1] "2.3."  "2.3."  "1.2."  "1.2."  "12.3." "12.3."