R语言:按指定规则提取并排序表格特定列内容的需求
解决方案
咱们可以分步骤来实现你要的需求,先理清楚核心逻辑:先按orderedNr排序数据,再根据每行的Type选择对应的列顺序,最后把每行的指定列拼接成字符串。
步骤1:正确读取并整理数据
首先修正原数据的读取方式,把列名和数据分开:
example <- read.table(text ="Nr orderedNr Type TextA TextB Year Date 1 469 1 A Text2 Text12 2012 01.01.2015 2 470 8 C Text9 Text19 1961 08.01.2015 3 471 2 A Text3 Text13 2012 02.01.2015 4 472 9 C Text10 Text20 1947 09.01.2015 5 474 3 B Text4 Text14 2005 03.01.2015 6 622 5 A Text6 Text16 1993 05.01.2015 7 623 6 B Text7 Text17 2009 06.01.2015 8 624 7 B Text8 Text18 1964 07.01.2015 9 625 4 C Text5 Text15 2009 04.01.2015 10 626 10 A Text11 Text21 1988 10.01.2015", header = TRUE)
步骤2:按orderedNr排序数据
用基础R的order()函数对数据框按orderedNr升序排列:
sorted_example <- example[order(example$orderedNr), ]
步骤3:定义不同Type对应的列顺序
根据你给出的规则,给每个Type指定要提取的列名顺序:
col_mapping <- list( A = c("orderedNr", "TextA", "TextB", "Year", "Date"), B = c("orderedNr", "TextB", "TextA", "Year", "Date"), C = c("orderedNr", "Year", "TextB", "TextA", "Date") )
步骤4:逐行处理并拼接成目标格式
用apply()逐行匹配列顺序后拼接字符串:
result <- apply(sorted_example, 1, function(row) { type <- row["Type"] cols <- col_mapping[[type]] paste(row[cols], collapse = ", ") }) # 输出最终结果 cat(paste(result, collapse = "\n"))
运行后的输出结果
1, Text2, Text12, 2012, 01.01.2015 2, Text3, Text13, 2012, 02.01.2015 3, Text14, Text4, 2005, 03.01.2015 4, 2009, Text15, Text5, 04.01.2015 5, Text6, Text16, 1993, 05.01.2015 6, Text17, Text7, 2009, 06.01.2015 7, Text18, Text8, 1964, 07.01.2015 8, 1961, Text19, Text9, 08.01.2015 9, 1947, Text20, Text10, 09.01.2015 10, Text11, Text21, 1988, 10.01.2015
补充:大数据量下的优化方案
如果你的数据量较大,用dplyr的向量化处理会更高效,代码也更直观:
library(dplyr) sorted_example %>% rowwise() %>% mutate( output = case_when( Type == "A" ~ paste(orderedNr, TextA, TextB, Year, Date, sep = ", "), Type == "B" ~ paste(orderedNr, TextB, TextA, Year, Date, sep = ", "), Type == "C" ~ paste(orderedNr, Year, TextB, TextA, Date, sep = ", ") ) ) %>% pull(output) %>% cat(sep = "\n")
内容的提问来源于stack exchange,提问作者Solana
相关产品推荐
相关产品推荐

