logo
down
shadow

replace a column in a dataframe given a corresponding vector in r


replace a column in a dataframe given a corresponding vector in r

By : user2951768
Date : November 18 2020, 03:49 PM
should help you out I'm looking to see if there is a quicker way to replace the days of the week in a R dataframe with a number. Essentially, the question I'm wondering is given one vector and a corresponding vector is there a quick way to apply a replacement to a dataframe. , Create a index of weekdays and match with the day_of_week column.
code :
Date <- as.Date('2014-12-29') #Monday 
Wdays <- weekdays(seq(Date, length.out=7, by= '1 day'))

df[,2] <- match(df[,2],Wdays)
df[,2] 
#[1] 2 3 4 5 6 7
as.numeric(factor(df$day_of_week, levels=c("Monday", "Tuesday",
    "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")))
#[1] 2 3 4 5 6 7
Un <- c('Tuesday',   'Wednesday', 'Thursday',  'Friday',   
        'Saturday',  'Sunday',    'Monday')
days_num <- c(2,3,4,5,6,7,1)
set.seed(24)
day_of_week <- sample(Un, 20, replace=TRUE)
unname(setNames(days_num, Un)[day_of_week])
#[1] 4 3 6 5 6 1 3 7 7 3 6 4 6 6 4 1 3 2 5 2
 library(qdap)
 as.numeric(mgsub(Un, days_num, day_of_week))
 #[1] 4 3 6 5 6 1 3 7 7 3 6 4 6 6 4 1 3 2 5 2
library(qdapTools)
day_of_week %l% data.frame(Un, days_num)
 #[1] 4 3 6 5 6 1 3 7 7 3 6 4 6 6 4 1 3 2 5 2


Share : facebook icon twitter icon
Replace values in column of a dataframe based on overlap with a vector

Replace values in column of a dataframe based on overlap with a vector


By : user3732263
Date : March 29 2020, 07:55 AM
this will help Good evening,
code :
#addones

lstcol <- list('cola', 'colb')
lstvec <- list(veca, vecb)

myfunc <- function(COL, VEC) {
  dataframe[[COL]][dataframe$ID %in% VEC] <<- 1
}

for(i in 1:length(lstcol)) {
  myfunc(lstcol[[i]], lstvec[[i]])
}

dataframe

#      ID cola colb colc cold cole colf
#1 XXXYYY    1    0    0    0    0    0
#2 XXYYXX    1    0    0    0    0    0
#3 XYXYXY    0    1    0    0    0    0
#4 YYYXXX    0    0    0    0    0    0

#remove lines

rowstoremove <- c('YYYXXX')
dataframe[!dataframe$ID == rowstoremove, ]

#       ID cola colb colc cold cole colf
# 1 XXXYYY    1    0    0    0    0    0
# 2 XXYYXX    1    0    0    0    0    0
# 3 XYXYXY    0    1    0    0    0    0
Replace matrix/dataframe values found in column i with i-th element of vector

Replace matrix/dataframe values found in column i with i-th element of vector


By : k3rni
Date : March 29 2020, 07:55 AM
I wish this help you I thought your proposed solution is wrong and here is a solution to thep problem described in your text. When which is called with .arr.ind=TRUE it returns a two column matrix which can be used for matrix or dataframe indexing as i,i reference. In this case you can also use its second column as an index to the v-object.
code :
> m[ which(m==0, arr.ind=TRUE) ] <- v[ which(m==0, arr.ind=TRUE)[,2] ]
> m
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    1    8    9
Pandas: Replace values within particular column of one dataframe based on a column in other dataframe

Pandas: Replace values within particular column of one dataframe based on a column in other dataframe


By : dreamers
Date : March 29 2020, 07:55 AM
may help you . You can use isin to check whether the values of one series or frame are in another one. To get a "not is in", simply negate the result with ~:
code :
>>> ~df1['Names'].isin(df2['Names'])
0     False
1     False
2     True
3     True
4     True
df1.loc[~df1['Names'].isin(df2['Names']), 'Names'] = 'Other'
Pandas Dataframe: Replace values in a dataframe with values from corresponding column vector of a different dataframe

Pandas Dataframe: Replace values in a dataframe with values from corresponding column vector of a different dataframe


By : Learning_Essential
Date : March 29 2020, 07:55 AM
around this issue One way is to transpose and merge. The only complication is that you need to ensure your merge column / index are both of the same type. Here we cast the index of the transposed dataframe explicitly to int.
code :
df2_t = df2.set_index('Item Number').T
df2_t.index = df2_t.index.astype(int)

res = df1.merge(df2_t, left_on='Item Number', right_index=True)

print(res)

   Item Number Price Location  Property1  Property2  Property3
0           33    $4   Boston        4.2        1.9        3.8
1           29    $2      NYC        2.4        5.2        8.9
Replace column names in dataframe based on a character vector that is ordered differently

Replace column names in dataframe based on a character vector that is ordered differently


By : Sam H
Date : March 29 2020, 07:55 AM
wish of those help My question is how to rename my column names based on a character vector while imposing the order of the vector on my data frame. I have read all the similar posts, yet non responds to my question. , We can use cols to reorder the columns in our data frame:
code :
df[,cols]
df[,c("B","A")]
df[,c("A","B")] 
Related Posts Related Posts :
  • Conditionally removing rows from a matrix in R
  • Using a loop to find P(-1.5<Y<1.5) for a range of sample sizes
  • R-Count and list the maximum count row by row
  • Include Iverson Bracket in R documentation
  • update a data frame and environment in R
  • How to write dynamic cumulative multiple in R
  • format time using as.POSIX in R
  • Change the class of multiple columns
  • Remove period and spaces within column headings nested in a list of data frames
  • R: error message --- package error: "functionName" not resolved from current namespace
  • labels with geom_text ggplot2
  • Passing mongodb ISODate in R
  • Importing "csv" file with multiple-character separator to R?
  • Change row names of a table obtained from a lm regression using xtable function
  • R language iterate over R object
  • How do you delete the header in a dataframe?
  • Re coding in R using complicated statement
  • accumulating functions and closures in R
  • How do you combine two columns into a new column in a dataframe made of two or more different csv files?
  • Twitter authentication fails
  • Summing Values of One Vector Conditional on Values of Another Vector
  • draw cube into 3D scatterplot in RGL
  • lme4 translate formula to code in 3-level model
  • How to draw single axis plot in R
  • Combine geom_tile() and facet_grid/facet_wrap and remove space between tiles (ggplot2)
  • Use snpStats with R version 3.0.1
  • Makefile gives strange error while compiling markdown file into .docx file
  • How to determine whether a points lies in an ellipse
  • Summarize data already grouped in r
  • Is the bigvis package for R not available for R version 3.0.1?
  • Operator overloading in R reference classes
  • How to enable user to switch between ggplot2 and gVis graphs in R Shiny?
  • Is there an easy way to separate categorical vs continuous variables into two dataset in R
  • Correct previous year by id within R
  • Installation of rdyncall package for R
  • ggplot2 plot that evaluates the percentage and mean of a third variable at intersecting points
  • Error Handling with Lapply
  • data.table - split multiple columns
  • How to compute the overall mean for several files in R?
  • R: Graph Plotting: Subscripts in the legend like LaTeX
  • Restructuring data in R
  • Distance of pointsfrom cluster centers after K means clustering
  • R incorrect value of date function
  • Package "Imports" not loading in R development package
  • r - run a user defined function several times by taking column elements as parameters
  • Create input$selection to subset data AND radiobuttons to choose plot type in Shiny
  • Generate crosstabulations from dataframe of categorical variables in survey
  • Restructure output of R summary function
  • New behavior in data.table? .N / something with `by` (calculate proportion)
  • search certain number vector in R
  • R version doesn't support quartz graphic device - RStudio won't plot
  • Referencing a function parameter in R
  • How to synchronize signals using a cross-correlation and FFT in R?
  • Plotting coefficients and corresponding confidence intervals
  • passing expressions to curve() within a function
  • More effective merging of matched column with duplicates in data.table
  • Easy way to export multiple data.frame to multiple Excel worksheets
  • R Foreach Iterator - Walkforward
  • Table format and output in R
  • Restructuring data and duplicating rows in R
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org