logo
down
shadow

reshape wide to long based on part of column name


reshape wide to long based on part of column name

Content Index :

reshape wide to long based on part of column name
Tag : r , By : jaredsmiller
Date : January 11 2021, 05:14 PM

help you fix your problem Using dplyr and tidyr, we can gather the data to long format, separate column name into different columns and spread them to wide format.
library(dplyr)
library(tidyr)

df %>%
  gather(key, value, -id) %>%
  separate(key, into = c("month", "part"), sep = "_") %>%
  spread(part, value)

#  id month head knee shoulder
#1  1   Feb   no   no       no
#2  1   Jan   no  yes      yes
#3  2   Feb  yes   no      yes
#4  2   Jan   no   no       no

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Reshape levels of a column (long) into new columns (wide)


Tag : r , By : jrf
Date : March 29 2020, 07:55 AM
may help you . I want to take the levels of a column in one DF and add each level as a new column in a new DF. Here is a toy dataset showing the source and ideal target DFs.
require(reshape2)

mydat <- recast(test_data,hour~ride)
mydat
  hour A B C
1    1 1 0 1
2    2 0 1 0
3    3 2 1 0
# 2nd part
for(i in 2:ncol(mydat)){
  for(ii in 1:nrow(mydat)){
    if(mydat[ii,i] > 0) {mydat[ii,i] <- 1}
  }
}
  hour A B C
1    1 1 0 1
2    2 0 1 0
3    3 1 1 0

reshape pandas wide column to long


Tag : python , By : hsdfhksh
Date : March 29 2020, 07:55 AM
will help you If possible one output column for teams use lreshape:
df = pd.lreshape(df, {'t':['t1','t2']})
print (df)
   buyprice  sellprice  tdate  tno      t
0        10         20   2017    1  teamA
1         5         10   2017    2  teamB
2        10         20   2017    1  teamB
3         5         10   2017    2  teamA
df = pd.concat([df.drop('t2', axis=1), df.drop('t1', axis=1)], ignore_index=True)
       .reindex_axis(df.columns, 1)
       .sort_values(['tno','tdate'])
print (df)
   tno  tdate  buyprice  sellprice     t1     t2
0    1   2017        10         20  teamA    NaN
2    1   2017        10         20    NaN  teamB
1    2   2017         5         10  teamB    NaN
3    2   2017         5         10    NaN  teamA

R: reshape dataframe from wide to long format based on compound column names


Tag : r , By : mylonov
Date : March 29 2020, 07:55 AM
I hope this helps . Yes you can do this with tidyverse !
You were close, you need to gather, then separate, then spread.
new_df <- mydf %>%
  gather(set, vars, 3:6) %>%
  separate(set, into = c('set', 'var'), sep = "_") %>%
  spread(var, vars)

R wide to long reshape with column names


Tag : r , By : Feroz
Date : October 29 2020, 05:01 AM
wish help you to fix your issue We can gather into 'long' format, then separate the 'key' column into two by splitting before the numeric part, spread it to 'wide' and change the 'key1' column to row names
library(tidyverse)
gather(df1) %>%
    separate(key, into = c('key1', 'key2'), sep="(?=\\d)") %>% 
    spread(key2, value) %>% 
    column_to_rownames('key1')
#  1  2
#A 10  5
#B 11  5
#C 21 10
df1 <- structure(list(A1 = 10L, A2 = 5L, B1 = 11L, B2 = 5L, C1 = 21L, 
     C2 = 10L), class = "data.frame", row.names = c(NA, -1L))

Reshape DataFrame from long to wide along one column


Tag : python , By : adbanginwar
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I am looking for a way to reconfigure Table A show below into Table B. , You can set the index appropriately and then unstack:
df

  type  x1  x2  x3
0    A   4   6   9
1    A   7   4   1
2    A   9   6   2
3    B   1   3   8
4    B   2   7   9

res = (df.set_index(['type', df.groupby('type').cumcount()])
         .unstack()
         .sort_index(level=-1, axis=1))

res.columns = res.columns.map(lambda x: x[0] + "'" * int(x[1]))    
res
       x1   x2   x3  x1'  x2'  x3'  x1''  x2''  x3''
type                                                
A     4.0  6.0  9.0  7.0  4.0  1.0   9.0   6.0   2.0
B     1.0  3.0  8.0  2.0  7.0  9.0   NaN   NaN   NaN
Related Posts Related QUESTIONS :
  • Create a filled area line plot with plotly
  • When do I need parentheses around an if statement to control the sequence of a formula in R?
  • my graph in ggplot2 contains an "e" character in y-axis
  • Making variables immutable in R
  • R: Difference between the subsequent ranks of a item group by date
  • Match data within multiple time-frames with dplyr
  • Conditional manipulation and extension of rows in data.table also considering previous extensions without for-loop
  • Conditional formula referring to preview row in DF not working
  • Set hoverinfo text in plotly scatterplot
  • Histogram of Sums from Categorical/Binary Data
  • Efficiently find set differences and generate random sample
  • Find closest points from data set B to point in data set A, using lat long in R
  • dplyr join on column A OR column B
  • Replace all string if row starts with (within a column)
  • Is there a possibility to combine position_stack and nudge_x in a stacked bar chart in ggplot2?
  • How can I extract bounding boxes in a row-wise manner using R?
  • How do I easily sum up values in different columns?
  • Reading numeric Date value from CSV file to data.frame in "R"
  • R programming: creating a stacked bar graph, with variable colors for each stacked bar
  • How to identify all columns that contain binary representation
  • Filter different groups by different factor levels
  • Saving .xlsx file to disc, form http post request
  • Add an "all" option under the filter that selects the number of rows displayed in a datatable
  • How to select second column of every xts in list
  • Generate a frequency dataframe out of an input dataframe
  • Why manual autocorrelation does not match acf() results?
  • Merge 3 dataframes which are different to each other
  • remove adjacent duplicates from string
  • How to change the position of stacked stacked bar chart in ggplot in R?
  • How to divide each of a range a variables by a second range of variables in R
  • Why do I need to assemble vector before scaling in Spark?
  • How to select individuals which appear in multiple groups?
  • How can I fill columns based on values in another column?
  • 32 bit R and 64 bit R: output differs
  • Remove a single backslash in paste0 output
  • ggplot2 different label for the first break
  • TSP in R, with given distances
  • How to find the given value from the range of values?
  • Solution on R group by issue _ multiple combination
  • Transform multiple columns with a function that uses different arguments per column
  • How can I parse a string with the format "1/16/2019 1:24:51" into a POSIXct or other date variable?
  • How to plot a box plot in R for outlier detection for a huge number of rows?
  • How to change column name according to another dataframe in R?
  • `sjPlot::tab_df()`--how to set the number of decimal places?
  • time average for specific time range in r
  • joining dataframes by closest time and another key in r
  • How to create nested for loop for a certain range
  • New category based on sequence of date ranges
  • how to extract formula from coxph model summary in R?
  • add row based on variable condition in R
  • Generating the sequence 111122222333334
  • Unable to use has_goog_key() in R
  • how to multiply each row with a scaler in corresponding column?
  • R is not recognizing levels of a factor as the same. Is there a way to do this?
  • Calculating mean of replicate experiment result values in a column based on multiple columns using R
  • Best method to extract the first instance of a string between specified keywords using data.table
  • ignore optional combination of alphanumeric characters in str_extract
  • Why tracemem shows two copies when modification occurs inside function body?
  • Can't use mppm on multitype point patterns
  • How to move selected matrix rows to top of matrix based on a selection vector of row names
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com