在 R 中粘贴 5 列组的问题 [英] Issue with pasting 5 columns groups in R
问题描述
我有一个如下所示的数据表.所有列都以字符为单位.
I have a data table like below. All columns are in characters.
Table:
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 .... V69
044 N 005 E 026 044 N 006 E 011
我想从 V29 开始将它们粘贴到 5 个列组中.例如,我想在 Table
中获取一个输出列,如下所示.
I want to paste them in 5 column groups starting from V29. For example I want to obtain an output column in Table
as shown below.
Table:
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 .... V69 Output
044 N 005 E 026 044 N 006 E 011 044N005E026-044N006E011-
我怎样才能在 R 中实现这一点.感谢任何帮助.
How can I achieve this in R. Any help is appreciated.
谢谢.
推荐答案
使用 DF
定义在注释末尾创建一个 sprintf
格式化字符串 fmt
然后运行它.
Using DF
defined in the Note at the end create a sprintf
formatting string fmt
and then run it.
如果 DF
中有 NA,那么它们将作为字符串 "NA"
出现在输出中.如果您希望完全省略它们,请在运行以下代码之前将它们替换为 DF
中的空字符串,即运行 DF[is.na(DF)] <- ""代码>首先.
If there are NA's in DF
then they will appear in the output as the string "NA"
. If you prefer to omit them completely then replace them with the empty string in DF
before running the code below, i.e. run DF[is.na(DF)] <- ""
first.
fmt <- paste(rep(strrep("%s", 5), ncol(DF)/5), collapse = "-") # %s%s%s%s%s-%s%s%s%s%s
Output <- do.call("sprintf", c(fmt, DF))
data.frame(DF, Output, stringsAsFactors = FALSE)
给予:
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 Output
1 044 N 005 E 026 044 N 006 E 011 044N005E026-044N006E011
或使用 Note 中的 DF2
代替 DF
我们得到:
or using DF2
from Note in place of DF
we get:
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 Output
1 044 N 005 E 026 044 N 006 E 011 044N005E026-044N006E011
2 045 S 006 F 027 045 S 007 F 012 045S006F027-045S007F012
数据表
如果,根据评论,您想使用 data.table 然后使用它(使用上面的 fmt
):
library(data.table)
DT <- data.table(DF)
DT[, Output:=do.call("sprintf", c(fmt, .SD))]
注意
Lines <- "
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38
044 N 005 E 026 044 N 006 E 011 "
DF <- read.table(text = Lines, header = TRUE, colClasses = "character")
Lines2 <- "
V29 V30 V31 V32 V33 V34 V35 V36 V37 V38
1 044 N 005 E 026 044 N 006 E 011
2 045 S 006 F 027 045 S 007 F 012"
DF2 <- read.table(text = Lines2, header = TRUE, colClasses = "character")
这篇关于在 R 中粘贴 5 列组的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!