需要将逗号分开的值转换为R数据框架

发布于 2025-02-03 06:51:37 字数 425 浏览 1 评论 0原文

我有一个看起来像这样的数据文件(TXT文件): 输入:aviles.txt 控制0.53、0.36、0.20,-0.37,-0.60,-0.64,-0.68,-1.27 膝盖0.73、0.31、0.03,-0.29,-0.56,-0.96,-1.61 眼睛-0.78,-0.86,-1.35,-1.48,-1.52,-2.04,-2.83 注意:每行的第一个值之后没有逗号。

数据框中的预期输出: 控制膝盖的眼睛 0.53 0.73 -0.78 0.36 0.31 -0.86 0.2 0.03 -1.35 -0.37 -0.29 -1.48 -0.6 -0.56 -1.52 -0.64 -0.96 -2.04 -0.68 -1.61 -2.83 -1.27

如何使用R进行操作?

I have a data file (txt file) that looks like this:
input: trials.txt
Control 0.53, 0.36, 0.20, -0.37, -0.60, -0.64, -0.68, -1.27
Knees 0.73, 0.31, 0.03, -0.29, -0.56, -0.96, -1.61
Eyes -0.78, -0.86, -1.35, -1.48, -1.52, -2.04, -2.83
Note: there is no comma after the first value in each row.

Expected Output in data frame:
Control Knees Eyes
0.53 0.73 -0.78
0.36 0.31 -0.86
0.2 0.03 -1.35
-0.37 -0.29 -1.48
-0.6 -0.56 -1.52
-0.64 -0.96 -2.04
-0.68 -1.61 -2.83
-1.27

How do I do that using R?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔岸观火 2025-02-10 06:51:37

我们可以使用.txt使用readlines读取文件,然后使用read.csv在删除初始单词以读取为data.frame。定界符t ranspose并设置列名称,并使用字符词提取的

lines <- readLines('trials.txt')
out <- setNames(as.data.frame(t(read.csv(text=sub("\\S+\\s+", "", lines), 
     header = FALSE))), sub("^(\\S+).*", "\\1", lines) )
row.names(out) <- NULL

- 输出

> out
  Control Knees  Eyes
1    0.53  0.73 -0.78
2    0.36  0.31 -0.86
3    0.20  0.03 -1.35
4   -0.37 -0.29 -1.48
5   -0.60 -0.56 -1.52
6   -0.64 -0.96 -2.04
7   -0.68 -1.61 -2.83
8   -1.27    NA    NA

或稍微更容易的选项是在上创建第一个空间,使用read.csv读取

out <- read.csv(text = sub("\\s+", ",", lines), header = FALSE)
out <- setNames(as.data.frame(t(out[-1])), out[[1]])
row.names(out) <- NULL

We may read the .txt file with readLines and then use read.csv after removing the initial word to read as data.frame making use of the delimiter ,, transpose and set the column names with the character word extracted

lines <- readLines('trials.txt')
out <- setNames(as.data.frame(t(read.csv(text=sub("\\S+\\s+", "", lines), 
     header = FALSE))), sub("^(\\S+).*", "\\1", lines) )
row.names(out) <- NULL

-output

> out
  Control Knees  Eyes
1    0.53  0.73 -0.78
2    0.36  0.31 -0.86
3    0.20  0.03 -1.35
4   -0.37 -0.29 -1.48
5   -0.60 -0.56 -1.52
6   -0.64 -0.96 -2.04
7   -0.68 -1.61 -2.83
8   -1.27    NA    NA

Or slightly easier option is to create the , at the first space, read with read.csv, and then set the names with the first column after transposing

out <- read.csv(text = sub("\\s+", ",", lines), header = FALSE)
out <- setNames(as.data.frame(t(out[-1])), out[[1]])
row.names(out) <- NULL
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文