[英]R Programming: Save data with different space lengths
I am trying to use R to save the data to a specific format for another analysis software. 我正在尝试使用R将数据保存为另一种分析软件的特定格式。 For example, my data is:
例如,我的数据是:
Jane 2 3 0 1
Joe 2 0 1 1
John 1 0 0 0
Jack 2 1 3 1
Jay 0 0 0 0
I would like to save the data to a .txt file in the following format: 我想将数据保存为以下格式的.txt文件:
Jane 2301
Joe 2011
John 1000
Jack 2131
Jay 0000
If I used write.table(....., sep = "")
, there will be no space between the names and numbers. 如果我使用
write.table(....., sep = "")
,则名称和数字之间将没有空格。 How can I save the file with space only between the name and numbers? 如何保存仅在名称和数字之间留有空格的文件? Thank you very much!
非常感谢你!
Jane 2 3 0 1
Joe 2 0 1 1
John 1 0 0 0
Jack 2 1 3 1
Jay 0 0 0 0
d <- read.table(con<-file("clipboard"), header = F)
d1 <- data.frame(col1 = d$V1,
col2 = paste0(d$V2,d$V3,d$V4,d$V5))
write.table(d1, sep = " ", row.names = F)
You will need to change the data format in R before saving it. 保存之前,您需要在R中更改数据格式。 Here, I am using
unite
from tidyr
to push all of those columns together (it ignores just V1
in this example, combining the rest) 在这里,我使用的
unite
从tidyr
推动所有这些列在一起(它忽略只是V1
在这个例子中,结合其余部分)
Read sample data: 读取样本数据:
df <-
read.table(
text =
"
Jane 2 3 0 1
Joe 2 0 1 1
John 1 0 0 0
Jack 2 1 3 1
Jay 0 0 0 0"
)
Run unite
运行
unite
df %>%
unite(singleData, -V1, sep = "")
Returns: 返回值:
V1 singleData
1 Jane 2301
2 Joe 2011
3 John 1000
4 Jack 2131
5 Jay 0000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.