आर में डेटा फ़्रेम कॉलम को कैसे स्टैक करें
अक्सर आप आर में दो या दो से अधिक डेटा फ़्रेम कॉलम को एक कॉलम में रखना चाह सकते हैं।
उदाहरण के लिए, हो सकता है कि आप इससे शुरुआत करना चाहें:
person trial outcome1 outcome2 A 1 7 4 A 2 6 4 B 1 6 5 B 2 5 5 C 1 4 3 C 2 4 2
उसके लिए:
person trial outcomes value A 1 outcome1 7 A 2 outcome1 6 B 1 outcome1 6 B 2 outcome1 5 C 1 outcome1 4 C 2 outcome1 4 A 1 outcome2 4 A 2 outcome2 4 B 1 outcome2 5 B 2 outcome2 5 C 1 outcome2 3 C 2 outcome2 2
यह ट्यूटोरियल दो तरीकों की व्याख्या करता है जिनका उपयोग आप ऐसा करने के लिए आर में कर सकते हैं।
विधि 1: बेस आर में स्टैक फ़ंक्शन का उपयोग करें
निम्नलिखित कोड दिखाता है कि बेस आर में स्टैक फ़ंक्शन का उपयोग करके कॉलम को कैसे स्टैक किया जाए:
#create original data frame data <- data.frame(person=c('A', 'A', 'B', 'B', 'C', 'C'), trial=c(1, 2, 1, 2, 1, 2), outcome1=c(7, 6, 6, 5, 4, 4), outcome2=c(4, 4, 5, 5, 3, 2)) #stack the third and fourth columns cbind (data[1:2], stack (data[3:4])) person trial values ind 1 A 1 7 outcome1 2 A 2 6 outcome1 3 B 1 6 outcome1 4 B 2 5 outcome1 5 C 1 4 outcome1 6 C 2 4 outcome1 7 A 1 4 outcome2 8 A 2 4 outcome2 9 B 1 5 outcome2 10 B 2 5 outcome2 11 C 1 3 outcome2 12 C 2 2 outcome2
विधि 2: Reshape2 के मेल्ट फ़ंक्शन का उपयोग करें
निम्नलिखित कोड दिखाता है कि reshape2 लाइब्रेरी में मेल्ट फ़ंक्शन का उपयोग करके कॉलम को कैसे स्टैक किया जाए:
#loadlibrary library(reshape2) #create original data frame data <- data.frame(person=c('A', 'A', 'B', 'B', 'C', 'C'), trial=c(1, 2, 1, 2, 1, 2), outcome1=c(7, 6, 6, 5, 4, 4), outcome2=c(4, 4, 5, 5, 3, 2)) #melt columns of data frame melt(data, id. var = c(' person ', ' trial '), variable. name = ' outcomes ') person trial outcomes value 1 A 1 outcome1 7 2 A 2 outcome1 6 3 B 1 outcome1 6 4 B 2 outcome1 5 5 C 1 outcome1 4 6 C 2 outcome1 4 7 A 1 outcome2 4 8 A 2 outcome2 4 9 B 1 outcome2 5 10 B 2 outcome2 5 11 C 1 outcome2 3 12 C 2 outcome2 2
आप मर्ज फ़ंक्शन के लिए संपूर्ण दस्तावेज़ यहां पा सकते हैं।
अतिरिक्त संसाधन
आर में दो कॉलम कैसे बदलें
आर में कॉलम का नाम कैसे बदलें
आर में विशिष्ट कॉलमों का योग कैसे करें