将不等数组的列转换为 R 中的单个值列

编程入门 行业动态 更新时间:2024-10-27 04:31:57
本文介绍了将不等数组的列转换为 R 中的单个值列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

作为此之后的下一步 previous question,假设有多个长度不同的数组列.例如:

As a next step after this previous question, assume that there are multiple columns of arrays that do not have the same length. For example:

Col_ACol_BCol_C
[0.1,0.5,0.7][1.54E12, 1.54E12, 1.54E12][1, 3, 4, 5}

我如何采用这种格式并将其重新格式化为以下格式,在适当的情况下为 Col_A 和 Col_b 提供 NA:

How can I take this format and reformat it to the following giving NAs to Col_A and Col_b where appropriate:

Col_ACol_BCol_C
0.11.54E121
0.51.54E123
0.71.54E124
不适用不适用5

此代码适用于所有数组相等的情况,但如果数组不相等则会抛出错误:

This code works for when all arrays are equal but will throw an error if the arrays are not equal:

library(dplyr) library(stringr) library(tidyr) df %>% mutate(across(everything(), str_extract_all, "(?<=\\[)[^]]+")) %>% unnest(c(NDVIs, dates)) %>% separate_rows(c(NDVIs, dates), sep=",\\s+", convert = TRUE)

推荐答案

我们可以使用 splitstackshape

library(splitstackshape) library(data.table) cSplit(setDT(df)[, lapply(.SD, gsub, pattern = "[][}]", replacement = "")], names(df), sep=",", fixed = FALSE, "long") # Col_A Col_B Col_C #1: 0.1 1.54e+12 1 #2: 0.5 1.54e+12 3 #3: 0.7 1.54e+12 4 #4: NA NA 5

数据

df <- structure(list(Col_A = "[0.1,0.5,0.7]", Col_B = "[1.54E12, 1.54E12, 1.54E12]", Col_C = "[1, 3, 4, 5}"), class = "data.frame", row.names = c(NA, -1L))

更多推荐

将不等数组的列转换为 R 中的单个值列

本文发布于:2023-07-10 08:29:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1089845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!