Change the class of multiple columns

Change the class of multiple columns

Content Index :

Change the class of multiple columns
Tag : r , By : Rit Li
Date : November 25 2020, 07:27 PM

Any of those help I have a data frame with 8 columns and 40 rows. All columns have numeric values. I need to change column 1 to 5 to character. I tried dplyr::mutate_at() but I cannot get it to work. I don't want to create new columns, but change the class of the existing ones. I keep getting the error Column col1 must be length 40 (the number of rows) or one, not 0 , Try doing it the way below:
df <- data.frame(a = c(0, 0, 0), b = c(1, 1, 1), c = c(0, 0, 1), d = c(1, 1, 1), e = c(0, 0, 0))

df_updated <- df %>% mutate_at(vars(1:5), as.character)

No Comments Right Now !

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

Share : facebook icon twitter icon

How to change a DataTable structure so columns values are in multiple columns?

Tag : chash , By : static AG
Date : March 29 2020, 07:55 AM
hop of those help? If i have a datatable with structure like that :
using System.Data;
public static class DataTableExtensionMethods
    public static DataTable TransposeIntegerColumnIntoColumns(this DataTable dt, int indexColumnToEstablishDuplicateRows, int integerColumnIdToTranspose, string transposedColumnName)
        //Protection if the column to transpose is not an integer or doesn't exist
        if (integerColumnIdToTranspose >= dt.Columns.Count) return null;
        var columnDataType = dt.Columns[integerColumnIdToTranspose].DataType;
        if (columnDataType != typeof(int)) return null;

        //Get max sessions number
        int maxColumnNumber = 0;
        foreach (DataRow dr in dt.Rows)
            int? number = dr.Field<int?>(integerColumnIdToTranspose);
            if (number != null)
                maxColumnNumber = Math.Max(maxColumnNumber, (int)number);

        //Protection if there are zero rows or the maxColumnNumber is 0
        if (dt.Rows.Count == 0 || maxColumnNumber == 0) return null;

        //Make a copy of the table so we can remove duplicate rows and add the transposed columns
        DataTable result = dt.Copy();

        //Add columns to store the session_ids
        for (int i = 1; i <= maxColumnNumber; i++)
            DataColumn dc = new DataColumn(transposedColumnName + i.ToString(), typeof(int));
            dc.DefaultValue = 0;
            //Possibly make an overloaded method that supports inserting columns

        //Remove rows with duplicated employees
        for (int i = 0; i < result.Rows.Count; i++)
            int duplicateRow = GetRowIndexById(result, indexColumnToEstablishDuplicateRows, result.Rows[i][indexColumnToEstablishDuplicateRows].ToString(), i + 1);
            if (duplicateRow > -1)

        //Populate the transposed columns with values in the integer Column To Transpose
        foreach (DataRow dr in dt.Rows)
            int? sessionNumber = dr.Field<int?>(integerColumnIdToTranspose);
            if (sessionNumber == null) continue;
            int rowIndex = GetRowIndexById(result, indexColumnToEstablishDuplicateRows, dr[indexColumnToEstablishDuplicateRows].ToString(), 0);

            result.Rows[rowIndex][transposedColumnName + sessionNumber.ToString()] = 1; //or +=1 if you want to increment the number

        //Remove the integerColumnIdToTranspose (again overload this method if you want to keep this column)

        return result;

   //Net 4 implementation with optional parameter
   //private static int GetRowIndexById(DataTable dt, int indexColumnToEstablishDuplicateRows, string id, int startLookAtRow = 0)
    private static int GetRowIndexById(DataTable dt, int indexColumnToEstablishDuplicateRows, string id, int startLookAtRow)
        for (int i = startLookAtRow; i < dt.Rows.Count; i++)
            if (dt.Rows[i][indexColumnToEstablishDuplicateRows].ToString() == id) return i;
        return -1;
private void button1_Click(object sender, EventArgs e)
    DataTable dt = GetData();
    DataTable result = dt.TransposeIntegerColumnIntoColumns(0, 3, "session_id");

private DataTable GetData()
    DataTable dt = new DataTable();
    dt.Columns.Add("emp_num", typeof(int));
    dt.Columns.Add("status", typeof(int));
    dt.Columns.Add("session_id", typeof(int));

    DataRow dr = dt.NewRow();
    dr["emp_num"] = 22;
    dr["name"] = "John";
    dr["status"] = 0;
    dr["session_id"] = 4;

    dr = dt.NewRow();
    dr["emp_num"] = 22;
    dr["name"] = "John";
    dr["status"] = 0;
    dr["session_id"] = 5;

    dr = dt.NewRow();
    dr["emp_num"] = 34;
    dr["name"] = "Moh";
    dr["status"] = 1;
    //dr["session_id"] = null;

    dr = dt.NewRow();
    dr["emp_num"] = 35;
    dr["name"] = "Ran";
    dr["status"] = 0;
    dr["session_id"] = 3;

    dr = dt.NewRow();
    dr["emp_num"] = 35;
    dr["name"] = "Ran";
    dr["status"] = 0;
    dr["session_id"] = 4;

    return dt;

Change class of multiple columns in data frame without for loop

Tag : r , By : user183825
Date : March 29 2020, 07:55 AM
hope this fix your issue OK I worked it out while writing the question, but figured it might as well go up in case it's use to anyone in future:
mydf[,2:3] <- lapply(mydf[,2:3], as.factor)

Change value at columns when finding values at column on the right for multiple pairs of columns without loop

Tag : matlab , By : scotta01
Date : March 29 2020, 07:55 AM
it fixes the issue You can locate all 4 and 5 values with ismember and then circshift the resulting boolean to the left and replace with NaN
bool = ismember(data, [4 5]);

shifted = circshift(bool, [0 -1]);

data(shifted) = NaN;
data(circshift(ismember(data, [4 5]), [0 -1])) = NaN;
to_be_nan = ismember(data(:,2:end), [4 5]);
to_be_nan(:,end+1) = false;

data(to_be_nan) = NaN;

How to change a specific string to NA in multiple columns and change column to numeric

Tag : r , By : Lars
Date : March 29 2020, 07:55 AM
will be helpful for those in need I have data in which some of the columns have a mix of character and numeric data. For example: , I create example data with
data <- read.table(text = "Sensor  Sensor2   Sensor3
                   Fail    5         Fail
                   Fail    5         Fail
                   Fail    5         Fail
                   Fail    5         Fail
                    5      5         Fail
                    6      5         Fail
                    8      5         Fail",
                   header = TRUE, stringsAsFactors = FALSE)
data$char <- letters[1:nrow(data)]
fail_cols <- sapply(data, function(x) any(grepl("Fail", x)))
to_num <- function(x) {
  as.numeric(gsub("Fail", NA, x))
data[fail_cols] <- lapply(data[fail_cols], to_num)
##   Sensor Sensor2 Sensor3 char
## 1     NA       5      NA    a
## 2     NA       5      NA    b
## 3     NA       5      NA    c
## 4     NA       5      NA    d
## 5      5       5      NA    e
## 6      6       5      NA    f
## 7      8       5      NA    g

dplyr rolling change multiple columns based on multiple columns

Tag : r , By : Ir0nh1de
Date : March 29 2020, 07:55 AM
around this issue Convert the data frame to a zoo object, run rollapplyr and convert back:

df %>%
   read.zoo %>%
   rollapplyr(12, function(x) colMeans(cor(x)), by.column = FALSE, fill = NA) %>%
Related Posts Related QUESTIONS :
  • `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
  • Combining expressions with a common operator
  • Passing string through multiple filters for matching
  • Convert two columns in R to rows of unique occurrence
  • How to create a dataframe using a function based on user-input?
  • How to access the visited vertices in a given shortest path using R igraph
  • Differences in Unicode character output with print()
  • Extracting Function or Objects from a String and then Piping Them with Magrittr/Dplyr
  • renderUI not evaluated until it is rendered
  • Find the maximum absolute value by row in an R data frame
  • Extracting data from irregular lists using purrr:map()
  • transforming data based on range of column in r
  • Identify and subset rows with some similar information
  • converting character from mongolite to timestamp in R
  • Create list from two vectors with every combo of each
  • Error in running a spread because of unique 'key combinations'; combining rows of data
  • visualize numerical strings as a matrixed heatmap
  • how to make a blocked matrix?
  • How to summarize with two functions using with dplyr
  • Dataframe is no longer the same after being saved to Excel and read back in
  • Create duplicate rows using based on availability of data
  • Keep empty groups when grouping with data.table in R
  • Grouping of Event Time Data based on multiple, iterative conditions
  • Formatting Numbers in Flextable for Specific Columns
  • How to store results from for-loop into a dataframe
  • How to select the values in my dataframe which has logical operator "<" (less than), divide them by two, an
  • Rowwise extract data between two strings
  • Convert a string separate by . and +
  • stacking function for values in R
  • dplyr coerces characters to factors
  • How do I use spread and group_by on a single row dataset
  • Replacing values in one matrix with values from another
  • Aggregate data and exclude duplicates in one column
  • Perform an R data.table binary search with OR select
  • How can I include a function in the Standard Deviation parameter of pnorm
  • How to get a tidy excel output of P values from R
  • Rotate boxplot legend (R, ggplot2)
  • dplyr::n() returns “Error: Error: n() should only be called in a data context ”
  • Extract fix columns and one variable column from a list of df´s in R
  • A function that can translate DNA sequence to binary code
  • I want to extract 365 netcdf files using loop
  • rvest vs RSelenium results for text extracting
  • Converting wide data to tall data
  • How to remove vertical white lines when using ggsave in R?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com