将txt文件读入R中的数据帧
我有一个以下格式的文本文件:将txt文件读入R中的数据帧,r,csv,R,Csv,我有一个以下格式的文本文件: "C1","name1","type1": 2 "C1","name2","type4": 6 "C2","name1","type2": 1 "C1","name3","type1": 10 我试过: db<- read.table("myfile.txt") 如何将最后两列存储为两个单独的列 C1 name1 type1 2 C1 name2 type4 6 C2 n
"C1","name1","type1": 2
"C1","name2","type4": 6
"C2","name1","type2": 1
"C1","name3","type1": 10
我试过:
db<- read.table("myfile.txt")
如何将最后两列存储为两个单独的列
C1 name1 type1 2
C1 name2 type4 6
C2 name1 type2 1
C1 name3 type1 10
谢谢也许
从tidyr
中分离出来的软件包可以帮助您
tidyr::separate(db, col = 3, into = c("type", "number"), sep = ":")
您可以在读取后拆分列,但请尝试read.csv
x = read.csv("myfile.txt", header = F, sep = ",")
y = matrix(unlist(strsplit(as.character(x$V3), ":")), ncol = 2, byrow = T)
x$V3 = y[, 3]
x$V4 = y[, 4]
V1 V2 V3 V4
1 C1 name1 type1 2
2 C1 name2 type4 6
3 C2 name1 type2 1
4 C1 name3 type1 10
你可以做:
d1 <- read.table(header=FALSE, sep=":", stringsAsFactors = FALSE, text=
' "C1","name1","type1": 2
"C1","name2","type4": 6
"C2","name1","type2": 1
"C1","name3","type1": 10')
d2 <- read.table(header=FALSE, sep=",", stringsAsFactors = FALSE, text=d1$V1)
cbind(d2, d1V2=d1$V2)
#> cbind(d2, d1V2=d1$V2)
# V1 V2 V3 d1V2
#1 C1 name1 type1 2
#2 C1 name2 type4 6
#3 C2 name1 type2 1
#4 C1 name3 type1 10
d1
x = read.csv("myfile.txt", header = F, sep = ",")
y = matrix(unlist(strsplit(as.character(x$V3), ":")), ncol = 2, byrow = T)
x$V3 = y[, 3]
x$V4 = y[, 4]
V1 V2 V3 V4
1 C1 name1 type1 2
2 C1 name2 type4 6
3 C2 name1 type2 1
4 C1 name3 type1 10
d1 <- read.table(header=FALSE, sep=":", stringsAsFactors = FALSE, text=
' "C1","name1","type1": 2
"C1","name2","type4": 6
"C2","name1","type2": 1
"C1","name3","type1": 10')
d2 <- read.table(header=FALSE, sep=",", stringsAsFactors = FALSE, text=d1$V1)
cbind(d2, d1V2=d1$V2)
#> cbind(d2, d1V2=d1$V2)
# V1 V2 V3 d1V2
#1 C1 name1 type1 2
#2 C1 name2 type4 6
#3 C2 name1 type2 1
#4 C1 name3 type1 10