【发布时间】:2016-10-22 09:16:58
【问题描述】:
我有一个大数据框,我希望字符串根据后缀(子字符串)在列中对齐,源数据框如下所示:
notst 代表其他要忽略的变量前缀
# col1 col2 col3
# notst-s1 notst-s2 notst-x3
# notst-s1 notst-x3 notst-a5
# notst-s2 notst-a5
# notst-x3 notst-a5
结果,应该是:
# col1 col2 col3 col4
# notst-s1 notst-s2 notst-x3
# notst-s1 notst-x3 notst-a5
# notst-s2 notst-a5
# notst-x3 notst-a5
编辑:
考虑整个后缀(“-”之后)。它没有数字。在某些情况下,应该匹配整个字符串 ("xxxx-spst") (*),因为字符串的 xxxx 部分有多个版本。
为:
df <- read.table(text="
col1 col2 col3
st1-ab stb-spst sta-spst
stc-spst sta-spst st4-ab
stb-spst st7-ab
st9-ba stb-spst",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)
可能的结果,可能是:(列名和顺序无关)
# col1 col2 col3 col4
# st1-ab stb-spst sta-spst
# st4-ab stc-spst sta-spst
# st7-ab stb-spst
# stb-spst st9-ba
(*) 请注意,在第 2 行 col2 中,“stc-spst”似乎放错了位置,但这不是问题,因为该行中不存在值 stb-spst,因此对于这种特殊情况,只有后缀(“spst”)很重要。换句话说,当整个字符串(前缀-后缀)与其他(在其他行)匹配时,它们应该在同一列,如果不是,当后缀匹配(其他行的)后缀时,它们应该在同一列柱子。生成的数据框应具有与原始数据框相同的行数和尽可能少的列数。
编辑。答案应该是通用的并且适用于:
df2 <- read.table(text="
col1 col2 col3 col4
st1-ab stb-spst sta-spst std-spst
stc-spst sta-spst st4-ab st2-ab
stb-spst st7-ab sa-ac
st9-ba stb-spst",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)
例如,也。 可能的结果:
# col1 col2 col3 col4 col5 col6 col7
# st1-ab stb-spst sta-spst std-spst
# st4-ab stc-spst sta-spst st2-ab
# st7-ab stb-spst sa-ac
# stb-spst st9-ba
示例 3
df3 <- read.table(text="
col1 col2 col3 col4
st1-ab stb-spst sta-spst std-spst
stb-spst sta-ab
sta-spst st7-ab sa-ac
sta-spst stb-spst",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)
想要的输出
col1 col2 col3 col4 col5
1 st1-ab sta-spst stb-spst std-spst
2 sta-ab stb-spst
3 sa-ac st7-ab sta-spst
4 sta-spst stb-spst
编辑示例 4。为了使任务更容易,您可以在函数中显式定义每行可能有多个可能前缀的后缀。在这个例子中(“spst”)。因此,任何后缀不同于“spst”的字符串每行应该只有一个可能的前缀,并且可以而且必须折叠到结果df中的一列中,作为所需输出中的col2。这不是我最初想要的,因为我会得到比预期更多的列。理想情况下,包含 spst 和不同前缀的字符串应该出现在尽可能少的列中。往上看)。
df4 <- read.table(text="
col1 col2 col3 col4
st1-ab stb-spst sta-spst std-spst
stb-spst st1-ab
sta-spst st7-ab sa-ac
sta-spst stb-spst st7-ab",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)
想要的输出
row_id col1 col2 col3 col4 col5
1 st1-ab sta-spst stb-spst std-spst
2 st1-ab stb-spst
3 sa-ac st7-ab sta-spst
4 st7-ab sta-spst stb-spst
【问题讨论】:
-
您能否为我们提供一些关于如何移动数据的逻辑?为什么要这样做?
-
@Ferroao 编辑后的新示例数据和该示例的预期输出令人困惑
-
它像以前一样具有前缀和后缀(由 - 分隔)。但后缀中没有数字。当多个匹配项(列 2 和 3)时,输出基于后缀,在某些情况下是整个字符串。
-
在示例 3 中,我认为第 2 行的输出 col 2 应该是 sta-ab(或者第 2 行的输入,col2 应该是 st2-ab)