简体   繁体   中英

update the value of a cell in a dataframe in R

I am trying to fill the values of a variable row by row for which I loop through the dataframe and when I have the value I want to fill I do this::

listadoProyectosPlanificados<-function(df){
variables<-names(df)
variablesAIgnorar<-c('Total','JefeProyecto','Ranking','Proyectos')
variablesATenerEncuenta<-subset(variables,!(variables %in% variablesAIgnorar))
for (indiceFila in 1:nrow(df)) {
 proyectos<-vector()
 for (indiceColumna in 1:length(variablesATenerEncuenta)) {
  if (df[indiceFila,variablesATenerEncuenta[indiceColumna]]!=0) {
    proyectos<-append(proyectos,variablesATenerEncuenta[indiceColumna])
  }
}
print(indiceFila)
print(ncol(df))
print(paste(proyectos,collapse = ', '))
df[indiceFila,ncol(df)]<-paste(proyectos,collapse = ', ')
}
}

印刷

But this sentence do nothing in df

df[indiceFila,ncol(df)]<-paste(proyectos,collapse = ', ')

but if I do this in consle df[1,49]<-paste(c('hola','adios'),collapse = ', ')

> df[1,49]
[1] "hola, adios"

it updates

any idea, please?

regards

Change MyDataFrame to the name of your data frame and it should work.

listadoProyectosPlanificados <- function(df){
  variables<-names(df)
  variablesAIgnorar<-c('Total','JefeProyecto','Ranking','Proyectos')
  variablesATenerEncuenta<-subset(variables,!(variables %in% variablesAIgnorar))
  for (indiceFila in 1:nrow(df)) {
    proyectos<-vector()
    for (indiceColumna in 1:length(variablesATenerEncuenta)) {
      if (df[indiceFila,variablesATenerEncuenta[indiceColumna]]!=0) {
        proyectos<-append(proyectos,variablesATenerEncuenta[indiceColumna])
      }
    }
    print(indiceFila)
    print(ncol(df))
    print(paste(proyectos,collapse = ', '))
    df[indiceFila,ncol(df)]<-paste(proyectos,collapse = ', ')
  }

  return( df ) #new statement
}

MyDataFrame <- listadoProyectosPlanificados(MyDataFrame)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM