मेरे पास एक डेटाफ्रेम है जो निम्न जैसा दिखता है। स्वास्थ्य, जानवरों, पर्यावरण और धन के माप के साथ कई चर (जैसे "सी" और "जेड") हैं। वास्तविक डेटाफ़्रेम में, ऐसे कई अन्य स्तंभ हैं जो इस पैटर्न का पालन नहीं करते हैं और एक दूसरे से जुड़े हुए हैं।
id c_health c_animals c_enviro c_money z_health z_animals z_enviro z_money
1 3 2 4 5 7 9 6 8
2 2 3 5 4 8 7 6 9
3 4 1 2 3 9 6 8 7
मैं इसे "साफ" बनाने के लिए डेटा को पुनर्व्यवस्थित करने का प्रयास कर रहा हूं। मुझे यकीन नहीं है कि मेरे वर्तमान डेटासेट में कई चर होने पर क्या करना है। इस प्रकार का परिणाम मैं अंततः समाप्त करना चाहूंगा:
id c z message
1 3 7 health
1 2 9 animals
1 4 6 enviro
1 5 8 money
2 2 8 health
2 3 7 animals
2 5 6 enviro
2 4 9 money
3 4 9 health
3 1 6 animals
3 2 8 enviro
3 3 7 money
यदि डेटाफ्रेम में केवल निम्नलिखित कॉलम शामिल हैं, तो मैं इसे निम्नलिखित तरीके से साफ कर सकता हूं:
id c_health c_animals c_enviro c_money
1 3 2 4 5
2 2 3 5 4
3 4 1 2 3
df <- df %>%
gather(., key = "question", value = "response", 2:5)
2 जवाब
आप gather
का उपयोग करने के साथ सही रास्ते पर हैं, लेकिन कॉलम नामों से उपसर्ग को विभाजित करने के लिए कुछ अतिरिक्त चरणों की आवश्यकता है। निम्नलिखित का प्रयास करें:
library(dplyr)
library(tidyr)
df = data.frame(
id = c(1,2,3),
c_health = c(3,2,4),
c_animals = c(2,3,1),
z_health = c(7,8,9),
z_animals = c(9,7,6),
stringsAsFactors = FALSE
)
output = df %>%
# gather on all columns other than id
gather(key = "question", value = "response", -all_of("id")) %>%
# split off prefix and rest of column name
mutate(prefix = substr(question,1,1),
desc = substr(question,3,nchar(question))) %>%
# keep just the columns of interest
select(id, prefix, desc, response) %>%
# reshape wider
spread(prefix, response)
अपडेट करें - अलग-अलग उपसर्ग लंबाई पर मेरी टिप्पणी सही उत्तर नहीं देती है। क्योंकि []
इंडेक्सिंग उस तरह से म्यूटेट के अंदर काम नहीं करता है। वही विचार लेकिन सही वाक्यविन्यास निम्नानुसार है:
output = df %>%
# gather on all columns other than id
gather(key = "question", value = "response", -all_of("id")) %>%
# split off prefix and rest of column name
mutate(split = strsplit(question, "_")) %>%
mutate(prefix = sapply(split, function(x){x[1]}),
desc = sapply(split, function(x){x[2]})) %>%
# keep just the columns of interest
select(id, prefix, desc, response) %>%
# reshape wider
spread(prefix, response)
आप इसे tidyr पैकेज और पिवट_लॉन्गर के साथ कर सकते हैं:
library(tidyr)
library(dplyr)
df %>%
pivot_longer(cols = 2:ncol(df),
names_to = c(".value", "message"),
names_sep = "_")