do.call('rbind', lapply(df, function(x) { # loop through vector df
x <- strsplit(x, "\ ")[[1]] # split string by spaces
x <- x[which(unlist(lapply(x, nchar)) > 0)] # remove zero length strings
x <- c(x[1:3], paste(x[4:length(x)], collapse = " ")) # collapse all elements from 4 to end
return(x) # return formatted vector
}))
# [,1] [,2] [,3] [,4]
# [1,] "24-March-2017" "text1" "874874455221112" "Text text text10"
# [2,] "25-March-2017" "text2" "54654656TEXT" "Text text 11"
# [3,] "24-March-2017" "text3" "874874455221112" "Text text text 12"
# [4,] "25-March-2017" "text4" "54654656TEXT" "Text text 13"
# [5,] "26-March-2017" "text3" "54654TEXT" "Text text text 14"
# [6,] "27-March-2017" "text5" "6546TEXT" "Text text text 15"
# [7,] "28-March-2017" "text6" "546476876586TExt" "Text text text 16"
# [8,] "29-March-2017" "text7" "23453453TEXT" "Text text 17"
基於@thelatemail評論
df <- read.table(text=df,fill=TRUE,header=FALSE)
df[, 4] <- apply(df[, 4:ncol(df)], 1, function(x) {
paste(x[ ! is.na(x) ], collapse = ' ') })
df <- df[, 1:4]
df
# V1 V2 V3 V4
# 1 24-March-2017 text1 874874455221112 Text text text10
# 2 25-March-2017 text2 54654656TEXT Text text 11
# 3 24-March-2017 text3 874874455221112 Text text text 12
# 4 25-March-2017 text4 54654656TEXT Text text 13
# 5 26-March-2017 text3 54654TEXT Text text text 14
# 6 27-March-2017 text5 6546TEXT Text text text 15
# 7 28-March-2017 text6 546476876586TExt Text text text 16
# 8 29-March-2017 text7 23453453TEXT Text text 17
數據:
df <- c("24-March-2017 text1 874874455221112 Text text text10",
"25-March-2017 text2 54654656TEXT Text text 11",
"24-March-2017 text3 874874455221112 Text text text 12",
"25-March-2017 text4 54654656TEXT Text text 13",
"26-March-2017 text3 54654TEXT Text text text 14",
"27-March-2017 text5 6546TEXT Text text text 15",
"28-March-2017 text6 546476876586TExt Text text text 16",
"29-March-2017 text7 23453453TEXT Text text 17")
'read.table(text = data,fill = TRUE,header = FALSE)'給你一個很好的R數據集,可以作爲轉換爲新格式的乾淨基礎。 – thelatemail
爲什麼不把它保存爲.csv,然後使用LibreOffice Calc加載它?它可以選擇加載由空格分隔的文本文件(以及其他字符),也可以選擇合併分隔符。稍後,您可以使用函數* concatenate *合併最後一列。 – Rodrigo