gpt4 book ai didi

string - R中用空格分割不均匀字符串

转载 作者:行者123 更新时间:2023-12-02 01:23:35 25 4
gpt4 key购买 nike

我读了很多关于在 R 中分割字符串的文章。但是,我遇到了一个错误,我认为这是由于变量读入 R 的方式造成的,即在某些情况下,日期后面有空格,因为 ID 较短。我试图将字符变量“VESSELID”拆分为 2 个新变量:“vesselID”和“DATE”。以下是我的数据集的一个子集。

> dput(df)
structure(list(SETID = c(24153L, 24187L, 24215L, 31990L, 31990L,
31995L, 31995L, 31995L, 31996L, 31996L, 31996L, 31997L, 31997L,
32002L, 32002L, 32002L, 32002L, 32003L, 32003L, 32003L), VESSELID = c("6830 2002/08/13 ",
"6830 2002/08/12 ", "6830 2002/08/15 ", "105372 2002/08/23",
"105372 2002/08/23", "104234 2002/07/20", "104234 2002/07/20",
"104234 2002/07/20", "104234 2002/07/21", "104234 2002/07/21",
"104234 2002/07/21", "104234 2002/07/22", "104234 2002/07/22",
"5744 2002/08/14 ", "5744 2002/08/14 ", "5744 2002/08/14 ",
"5744 2002/08/14 ", "5744 2002/08/13 ", "5744 2002/08/13 ",
"5744 2002/08/13 ")), .Names = c("SETID", "VESSELID"), row.names = c(1L,
2L, 3L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 25L, 26L), class = "data.frame")

我确实尝试了以下方法:

library(reshape2)
test <- data.frame(df, colsplit(df$VESSELID, split= " ",names=c("vesselID","DATE")))

但是,我收到此错误消息:

Error in colsplit(log21$VESSELID, split = " ", names = c("vesselID", "DATE")) : 
unused argument(s) (split = " ")

split 命令似乎无法正常工作。我不知道如何修复我的字符串。

最佳答案

我实际上只会在该列上使用 read.table ,如下所示。假设您的数据集名为“mydata”:

mydata.new <- cbind(mydata[-2], 
read.table(text = as.character(mydata$VESSELID),
strip.white=TRUE, header = FALSE))
names(mydata.new)[2:3] <- c("VesselID", "Date")
mydata.new
# SETID VesselID Date
# 1 24153 6830 2002/08/13
# 2 24187 6830 2002/08/12
# 3 24215 6830 2002/08/15
# 10 31990 105372 2002/08/23
# 11 31990 105372 2002/08/23
# 12 31995 104234 2002/07/20
# 13 31995 104234 2002/07/20
# 14 31995 104234 2002/07/20
# 15 31996 104234 2002/07/21
# 16 31996 104234 2002/07/21
# 17 31996 104234 2002/07/21
# 18 31997 104234 2002/07/22
# 19 31997 104234 2002/07/22
# 20 32002 5744 2002/08/14
# 21 32002 5744 2002/08/14
# 22 32002 5744 2002/08/14
# 23 32002 5744 2002/08/14
# 24 32003 5744 2002/08/13
# 25 32003 5744 2002/08/13
# 26 32003 5744 2002/08/13

关于string - R中用空格分割不均匀字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com