3

I have a dataframe that includes a series of information that identifies a group of people by their current board memberships. It looks like this:

company_board <- c("company1", "company2", "company3; company 1", "", "")
nonprofit_board <- c("nonprofit1", "", "nonprofit5; nonprofit2", "", "nonprofit3")
df <- data.frame(company_board, nonprofit_board, stringsAsFactors = FALSE)

I want to convert these into simple 1 if there is information in the cell or 0 if there is no data recorded. So for the example I've just given:

company_board <- c("1", "1", "1", "0", "0")
nonprofit_board <- c("1", "0", "1", "0", "1")
df <- data.frame(company_board, nonprofit_board, stringsAsFactors = FALSE)

I know how to use str_extract with [:alnum:] to get the cells that should be 1 but I can't figure out how to then replace these cells with 1 (and the remainder with 0). Any help would be greatly appreciated!

3 Answers 3

2

We can also convert to matrix and apply nchar directly

+(nchar(as.matrix(df)) > 0)
#     company_board nonprofit_board
#[1,]             1               1
#[2,]             1               0
#[3,]             1               1
#[4,]             0               0
#[5,]             0               1
Sign up to request clarification or add additional context in comments.

Comments

1

An easy way to make it is using nzchar

dfout <- +data.frame(Map(nzchar,df))

such that

> dfout
  company_board nonprofit_board
1             1               1
2             1               0
3             1               1
4             0               0
5             0               1

Comments

1

You can use sapply and test if nchar is more than 0.

sapply(df, function(x) +(nchar(x)>0))
#     company_board nonprofit_board
#[1,]             1               1
#[2,]             1               0
#[3,]             1               1
#[4,]             0               0
#[5,]             0               1

Or shorter:

+(sapply(df, nchar)>0)

In case you have " " you can add something like trimws:

sapply(df, function(x) +(nchar(trimws(x))>0))

Or using nzchar seen already in @ThomasIsCoding's answer.

+sapply(df, nzchar)

1 Comment

Perfect thanks! I'll accept this answer as soon as the system allows me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.